【问题标题】:Triggering an event as soon as the element is scrolled on to the screen [duplicate]元素滚动到屏幕后立即触发事件[重复]
【发布时间】:2014-08-28 01:47:48
【问题描述】:
我有一个 ID 为 ig-container 的元素。我想添加类似的类
$("#ig-container").addClass("animated bounceInRight");
该元素在屏幕上可见。通过这样做,当用户滚动该元素时,我可以在该元素上实现动画。
我该怎么做?
PS:我尝试使用 .is(":visible") 但它没有按我的意愿工作,因为它会检查元素是否存在于 DOM 中。
【问题讨论】:
标签:
jquery
html
animation
parallax
【解决方案1】:
这里是我自己的例子,确保你使用 doctype 否则 $(window).height() 返回文档高度
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(window).scroll(function(){
if(($('.diff').offset().top+$('.diff').height()) < ($(window).scrollTop() + $(window).height()))
{
$('.diff').addClass('green');
}
});
});
</script>
<style>
.green { background:#0F0 !important; }
</style>
</head>
<body>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">1</div>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">2</div>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">3</div>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">4</div>
<div class="diff" style="min-height:250px; margin-bottom:10px; background:#00F;">THIS ONE</div>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">1</div>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">1</div>
<div style="min-height:250px; margin-bottom:10px; background:#F00;">1</div>
</body>
</html>
慢慢滚动,你应该会看到,一旦你通过了蓝色的 div,它就会变成绿色
希望对你有帮助
汤姆