正如评论的那样,您可能希望将滚动与实际的 CSS3 动画结合起来(在下面,最终是滚动时的 div 位置),这在之前的答案中是缺乏的:
$(window).scroll(function(){
var top = $(this).scrollTop();
if(top > 150){
document.getElementById("some_div_element").style.animationName = "some_animation_name";
}
});
some_div_element 的 css 样式属性可以用 some_animation_name 以外的其他东西初始化,因此一旦滚动位置更改了此样式属性,就会触发动画:
div.some_div_element {
background-color:rgb(140, 20, 20);
animation-name: undefined_bla;
}
...并与some_animation_name 的动画定义一起使用,例如:
@keyframes some_animation_name {
from {background-color:rgb(140, 20, 20);}
to {background-color:rgb(200, 20, 20);}
}
然而,对于 div 元素,它通常不是滚动位置本身,而是元素到例如显示的页面顶部的距离,这对启动动画很重要:
window.onscroll = function() {dist_to_top_function()};
function dist_to_top_function() {
var dist = document.getElementById("some_div_element").getBoundingClientRect().top;
if(dist < 600){ // distance in px
document.getElementById("some_div_element").style.animationName = "some_animation_name";
}
}
js if 语句还可以包含对 div 样式的修改,以使其永久匹配动画的最终结果,例如,
...
document.getElementById("some_div_element").style.backgroundColor= "rgb(200, 20, 20);";