功能: 当用户看到某个div(向下滚动到它)时,我想更改某个项目的类。
我现在该怎么做:我正在使用这个很好的脚本(http://code.google.com/p/jquery-appear/),当div对用户可见时,它只能触发一个jquery事件。然而它只发射一次。因此,如果向下滚动页面,jquery就可以正常执行了。但是,如果我向上滚动然后再向下滚动它就会发生火灾。这是我的jquery:
$('#myDiv').appear(function() {
$("#aDiv").addClass("active");
});
我想做什么:每当“myDiv”出现时让脚本执行,而不仅仅是第一次。
有没有人知道如何做到这一点?
答案 0 :(得分:6)
判断div是否可见,你可以:
$(window).scroll(function(event) {
console.log($(".target").offset().top < $(window).scrollTop() + $(window).outerHeight());
});
所以,我认为你不需要任何插件。
只需通过以下表达式来判断:
if($(".target").offset().top < $(window).scrollTop() + $(window).outerHeight()) {
// something when the .target div visible
} else {
// something when the .target div invisible
}
答案 1 :(得分:4)
通过查看jquery-appear plugin的源代码,可以传递参数one
,仅触发事件一次(one: true
),或每次出现时(one: false
)
$('#myDiv').appear(function() {
$("#aDiv").addClass("active");
}, {
one: false
});
答案 2 :(得分:3)
我使用类似的插件但是这使用了bind方法并使用了一个事件 - &gt; http://remysharp.com/2009/01/26/element-in-view-event-plugin/
样本用法:
$('div').bind('inview', function (event, visible) {
if (visible == true) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});
答案 3 :(得分:1)
This可能对您有用。
无论如何,你可以在没有插件的情况下使用简单的表达式来实现:
var elem_top = $("some_element").offset().top;
var elem_height = $("some_element").height();
var wind_height = $(window).height();
var scrollTop = $(window).scrollTop;
if (elem_top > (wind_height + scrollTop) &&
!(elem_top + elem_height) < wind_scrollTop)
{
//The element is inside the screen (e.g. it is directly visible)
}