从事业余爱好元素以学习一些 html、css 和 js。
一直在尝试解决一个奇怪的 CSS 动画问题。第一次迭代后,它有时会在动画中间出现或消失,有时会快速闪烁。在多个浏览器和多台计算机/设备上尝试过,结果都一样。
JSFiddle here (删除了一些代码)和实例 here .
index.html
...
<body onload="init()">
<div class="leftanimation">Cool Gliding Text</div>
<div class="leftanimation">Lorem Ipsum Dolor Sit</div>
<div class="leftanimation">How Cool Is This?</div>
<div class="leftanimation">Wwiiiieeee! </div>
<div class="leftanimation">Sssssswwwwoooosssshhh!</div>
<div class="leftanimation">Drive by text!</div>
<div class="leftanimation">More example text ...</div>
<div class="leftanimation">Last test text.</div>
...
script.js
function init() {
var a = document.getElementsByClassName("leftanimation");
for (i = 0; i < a.length; i++){
a[i].addEventListener("animationiteration", updateAnim);
}
}
function updateAnim() {
this.style.left = Math.random() * 7 + "%";
//this.style.transform = "rotate(-90deg) translate(0px, " + Math.random() * 50 + 10 + "px)";
this.style.fontSize = Math.floor(Math.random() * 100) + 30 + "px";
this.style.opacity = Math.random() * 0.5;
this.style.animationDuration = Math.floor(Math.random() * 30) + 20 + "s";
if (Math.floor(Math.random() * 2) == 1) {
this.style.animationDirection = "normal";
} else {
this.style.animationDirection = "reverse";
}
}
样式.css
.leftanimation {
position: fixed;
transform: rotate(-90deg);
transform-origin: 5% 50%;
animation: glide 0.01s infinite;
animation-direction: alternate;
backface-visibility: hidden;
white-space: nowrap;
opacity: 0;
font-size: 20px;
z-index: -2;
}
@keyframes glide {
0% { top: -150%; animation-timing-function: ease-in-out; }
100% { top: 250%; animation-timing-function: ease-in; }
}
知道为什么会这样吗?
更新
如果我从 updateAnim()
中删除 animationDuration
,奇怪的行为似乎就会消失。但是,这并不能解决我的问题,因为我希望动画随机化。
也许处理 css 动画太多了?
最佳答案
只是一些提示:如果您使用 addEventListener(),您应该将它们收集在一个数组中,以便在需要时删除它们。
var eventListener = [];
element.addEventListener(event,callback,false);
eventListener.push([element,event,callback]);
要删除它们只需遍历数组:
while(var current = eventListener.pop()){
current[0].removeEventlistener(current[1],current[2]);
}
这只是为了从头开始学习。
和:
Math.floor(Math.random() * 2) == 1
应该是
Math.floor(Math.random() * 2) === 1
如果我看对了,您的问题发生在设置 animationDirection 时。它将状态切换为 css 给出的默认状态,然后以相反的顺序运行新动画。
尝试隐藏元素并设置动画开始的起始位置。之后显示元素并开始动画。也许将 animationStart 包裹在一个
setTimeout(function(){
// setAnimationProperty etc
},0);
关于javascript - CSS 动画表现怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36520569/