在一个业余爱好项目上学习一些html,css和js。CSS动画行为怪异
一直试图解决一个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";
}
}
的style.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; }
}
任何想法WH它的行为是这样吗?
更新
怪异的行为似乎消失了,如果我从updateAnim()
删除animationDuration
。但是,这并不能解决我的问题,因为我希望动画是随机的。
也许它只是太多处理的CSS动画?
,而不是'Math.floor的animationStart(的Math.random()* 2)=== 1'你可以只使用'的Math.random()<0.5' – vahanpwns
@ user2429266感谢提示,总是赞赏。动画是背景的一部分,所以我会很懒,不会删除事件侦听器。我知道资源处理很重要。 问题出现在我开始更改animationDirection之前。并且在更改属性之前隐藏文本似乎也不起作用(不确定我是否正确隐藏了它)。 –
@vahanpwns我会用它,但是我会把它改成'>'嘿嘿。 –