列表项在上下移动操作时,增加平滑过渡的效果
效果图
主要实现平滑过渡移动效果,样式有点丑,自己可以美化
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>列表项平滑过渡上下移动</title>
<style>
.move {
width: 400px;
height: 200px;
margin: 50px auto;
list-style: none;
position: relative;
}
.move li {
width: 100%;
height: 40px;
padding-left: 40px;
line-height: 40px;
position: absolute;
transition: all 500ms ease;
}
.move li button:first-child {
margin-left: 240px;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="container">
<ul class="move">
<li style="background: red;">苹果<button class="up">上移</button><button class="down">下移</button></li>
<li style="background: yellow;">香蕉<button class="up">上移</button><button class="down">下移</button></li>
<li style="background: blue;">橘子<button class="up">上移</button><button class="down">下移</button></li>
<li style="background: green;">西瓜<button class="up">上移</button><button class="down">下移</button></li>
<li style="background: gray;">菠萝<button class="up">上移</button><button class="down">下移</button></li>
</ul>
</div>
</body>
<script src="./js/jquery-3.3.1.js"></script> //引入自己的jquery库
<script>
$(function () {
$(".move li").each(function (index, ele) {
$(this).css({
"top": index * 40 + 'px'
});
})
//上移
$(".up").click(function () {
var $li = $(this).parent();
var $prev = $li.prev();
var $index = $li.index();
if ($index != 0) {
var $top = parseInt($li.css("top").slice(0, -2));
var $prevTop = parseInt($prev.css("top").slice(0, -2));
$li.css('top', ($top - 40) + "px");
$prev.css('top',($prevTop + 40) + "px");
//添加一个异步,间隔时间和css过渡一样,否则不会有平滑过渡效果
setTimeout(() => {
$prev.before($li);
}, 500);
}
});
//下移
var $len = $(".down").length;
$(".down").click(function () {
var $li = $(this).parent();
var $index = $li.index();
var $next = $li.next();
if ($index != $len - 1) {
var $top = parseInt($li.css("top").slice(0, -2));
var $nextTop = parseInt($next.css("top").slice(0, -2));
$li.css('top', ($top + 40) + "px");
$next.css('top', ($nextTop - 40) + "px");
setTimeout(() => {
$next.after($li);
}, 500);
}
});
})
</script>
</html>