我想知道有没有一种方法可以使用CSS动画使HTML元素消失。因此,当元素通过某些脚本从页面中移除时,在元素实际被移除之前应该显示动画。
这个是否容易实现?或者我需要为我的脚本设置一个计时器,开始一个持续X时间的动画,并在X时间后移除元素?
我想知道有没有一种方法可以使用CSS动画使HTML元素消失。因此,当元素通过某些脚本从页面中移除时,在元素实际被移除之前应该显示动画。
这个是否容易实现?或者我需要为我的脚本设置一个计时器,开始一个持续X时间的动画,并在X时间后移除元素?
我会在关键帧上做些花哨的东西
@keyframes myAnimation{
0%{
opacity: 1;
transform: rotateX(90deg);
}
50%{
opacity: 0.5;
transform: rotateX(0deg);
}
100%{
display: none;
opacity: 0;
transform: rotateX(90deg);
}
}
#myelement{
animation-name: myAnimation;
animation-duration: 2000ms;
animation-fill-mode: forwards;
}
如果脚本实际上是要删除 DOM 元素,我认为没有办法让它渐变消失。我认为定时器是你唯一的选择。
//jQuery
$(document).ready(function() {
var target = $("#div");
$("#btn").click(function() {
removeElement(target);
});
});
function removeElement(target) {
target.animate({
opacity: "-=1"
}, 1000, function() {
target.remove();
});
}
div {
width: 100px;
height: 100px;
background-color: #000;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div id="div"></div>
<input type="button" value="fadeout" id="btn">
</body>
</html>
使用如下代码来实现过渡效果:
function waithide()
{
var obj = document.getElementById("thisone");
obj.style.opacity = '0';
window.setTimeout(
function removethis()
{
obj.style.display='none';
}, 300);
}
div
{
height:100px;
width :100px;
background:red;
display:block;
opacity:1;
transition : all .3s;
-wekit-transition : all .3s;
-moz-transition : all .3s;
}
<div id="thisone" onclick="waithide()"></div>
display: none
隐藏它),并且我想知道是否有一种解决方案可以不用JS的setTimeout()
。但我想我会选择使用timeout的方式。 - Froxxanimation
属性会被触发。但是当元素被删除时,就有点困难了,因为似乎没有集成的监听器。我的问题是是否有我不知道的监听器。但是看起来并不是这样,所以我需要设置一个延迟元素删除的超时。 - Froxx我认为你需要分两步进行。先进行动画效果,然后在动画完成后移除元素。请参考下面的函数。也许可以将它制作成一个jQuery插件呢?
<style>
#test{
background: red;
height: 100px;
width: 400px;
transition: height 1s;
}
#test.hide {
height: 0;
}
</style>
<div id="test"> </div>
<button>Hide the Div</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script>
$('button').click(function(){
removeWithAnimate('#test');
});
function removeWithAnimate(id){
$(id).addClass('hide');
setTimeout( function(){
$(id).remove()
},1000);;
}
</script>
$('button').click(function() {
removeWithAnimate('#test');
});
function removeWithAnimate(id) {
$(id).addClass('hide');
setTimeout(function() {
$(id).remove()
}, 1000);;
}
#test {
background: red;
height: 100px;
width: 400px;
transition: height 1s;
}
#test.hide {
height: 0;
}
<div id="test"> </div>
<button>Hide the Div</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
transition: .5s;
不可见:
opacity: 0;
可见:
opacity: 1;
transition会使得元素平滑地出现和消失。