当元素显示从none变为其他值时,其动画(如果有的话)激活。 有谁知道如何防止这种情况?
同样很高兴理解为什么会这样。是因为DOM正在被改造?
这是我的意思参考的例子:
https://jsfiddle.net/darlyp/2p2q767r/
HTML
.red-square{
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
animation: 1s both moveSquare 1;
}
@keyframes moveSquare{
0%{
margin-left: 0px;
}
50%{
margin-left: 400px;
}
100%{
margin-left: 0px;
}
}
CSS
document.getElementById('btn').addEventListener("click", function() {
var currentDisplay = document.querySelector('.red-square').style.display;
if (currentDisplay === 'none') {
document.querySelector('.red-square').style.display = 'inline-block';
} else {
document.querySelector('.red-square').style.display = 'none';
}
})
JS
?123
答案 0 :(得分:2)
显示时,您可以将animation-play-state
设置为paused
。
document.getElementById('btn').addEventListener("click", function() {
var currentDisplay = document.querySelector('.red-square').style.display;
if (currentDisplay === 'none') {
document.querySelector('.red-square').style.display = 'inline-block';
document.querySelector('.red-square').style.animationPlayState = 'paused';
} else {
document.querySelector('.red-square').style.display = 'none';
}
})

.red-square{
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
animation: 1s both moveSquare 1;
}
@keyframes moveSquare{
0%{
margin-left: 0px;
}
50%{
margin-left: 400px;
}
100%{
margin-left: 0px;
}
}

<div class="red-square"></div>
<br/>
<button id="btn">
Hide and Show square
</button>
&#13;
答案 1 :(得分:1)
另一种方法是切换opacity
,并在隐藏时将height
更改为0
,这样它就不会占用页面上的任何空间
document.getElementById('btn').addEventListener("click", function() {
document.querySelector('.red-square').classList.toggle('hide');
})
&#13;
.red-square {
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
animation: 1s both moveSquare 1;
}
@keyframes moveSquare {
0% {
margin-left: 0px;
}
50% {
margin-left: 400px;
}
100% {
margin-left: 0px;
}
}
.hide {
opacity: 0;
height: 0;
}
&#13;
<div class="red-square"></div>
<br/>
<button id="btn">
Hide and Show square
</button>
&#13;