<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container py-5 my-5">
<button class="btn mb-3 btn-primary btn-in">In</button>
<div class="position-relative">
<div class="box box-in"></div>
</div>
</div>
<div class="container py-5 my-5">
<button class="btn mb-3 btn-danger btn-out">Out</button>
<div class="position-relative">
<div class="box box-out"></div>
</div>
</div>
<style type="text/css">
.box {
width: 100px;
height: 100px;
position: absolute;
}
.box-in {
background-color: blue;
opacity: 0;
}
.box-out {
background-color: red;
opacity: 1;
}
.out {
animation: out 1s;
}
.in {
animation: in 1s;
}
@keyframes out {
from {
left: 0px;
}
to {
left: 70px;
opacity: 0;
}
}
@keyframes in {
from {
left: -70px;
}
to {
left: 0px;
opacity: 1;
}
}
</style>
<script>
$('.btn-out').click(function() {
$('.box-out').addClass('out')
setTimeout(function() {
$('.box-out').removeClass('out')
}, 1000)
})
$('.btn-in').click(function() {
$('.box-in').addClass('in')
setTimeout(function() {
$('.box-in').removeClass('in')
}, 1000)
})
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js"></script>
</body>
</html>
现在每次动画结束后,div都会回到原先的位置
如何在动画结束后保留样式? 如left: -70px;
你把动画的结束属性作为初始属性,这样动画结束后就会回到你最开始设置的属性上,点击demo查看,如果你是想一开始不显示,触发动画之后才停留在结束属性上,那就在js上在搞个变量判断下是否第一次点击
你现在的问题是,你每次在动画结束的时候就会把animation这个动画移除掉,自然就不会保留动画中的属性了,你得先给box设置一个可以回来的初始值