jquery移除一个div,并用动画重新排列下面的div



我有一个卡片网格,上面有一个按钮,可以通过动画移除每一张卡片。我选择将宽度减小到0,以便右侧(同一行(的牌向左滑动并占据移除的牌位。我想实现的是将下一行的第一个元素动画化为上一行的最后一个位置(移除卡片的那个位置(。我能提供的最好的例子是Vivaldi浏览器的主页,在那里你可以删除一个快速拨号小部件,下面的小部件可以动画到它们的新位置。

CodePen中的这个例子就是我目前所拥有的。

$(document).ready(function() {

const content = $('#inner-content');
let listCourses = '';

let courses = [
{ title: 'html' }, 
{ title: 'css' }, 
{ title: 'javascript' }, 
{ title: 'python' }, 
{ title: 'react' }, 
{ title: 'node' }, 
{ title: 'angular' }, 
{ title: 'SEO' }, 
{ title: 'UX/UI' }, 
{ title: 'jQuery' }, 
{ title: 'SQL' }, 
{ title: 'noSql' }
]

courses.forEach((course) => {
let newCourse = `
<div class="course-container">
<div class="inner-container">
<h2>${course.title}</h2>
<button class="courses-control"> Remove </button>
</div>
</div>
`;
listCourses += newCourse;
});
content.html(listCourses);
$('.courses-control').on('click', function(e){
$(this)
.parents('.course-container').animate({
'width': '0px',
'padding': '12px 0px',
'opacity': '0'}, function() {
$(this).remove();
});
})
});
* {
box-sizing: border-box;
}
body { font-family: 'lato'; }
#inner-content {
display: flex;
flex-wrap: wrap;
}
.centered {
max-width: 960px;
margin: auto;
}
.course-container {
width: 25%;
padding: 12px;
overflow: hidden;
}
.inner-container {
overflow: hidden;
text-align: center;
border: 1px solid gray;
border-radius: 6px;
padding: 12px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>

<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Courses</h1>
<div id="inner-content" class="centered">

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>

将forEach循环更改为具有索引,并为每个按钮提供一个id:

courses.forEach((course, index) => {
let newCourse = `
<div class="course-container">
<div class="inner-container">
<h2>${course.title}</h2>
<button id="${index}" class="courses-control"> Remove </button>
</div>
</div>
`;
listCourses += newCourse;
});

然后在点击功能之后:

$(this)
.parents('.course-container').animate({
'width': '0px',
'padding': '12px 0px',
'opacity': '0'
}, function () {
$(this).remove();
});

添加以下内容:

$(`#${Number(this.id) + 4}`).parents('.course-container').animate({
'margin-top': '-100px',
'z-index': '1',
'opacity': '0'
}, 500, function () {
$(this).css({ 'margin': '0px', 'opacity': '1' });
});

试试看,告诉我你的想法。。。

最新更新