我正在使用以下脚本来查找是否有任何带有“.wew”类的div在视口视图中,如果是,则会添加“inview”类。
这很好但我使用全屏高度div并且它一次将类添加到2个div,可能是因为它检查div是否在屏幕的顶部或底部可见。有没有办法修改它,只有当div在窗口顶部的100px范围内时才会激活它?
CODE:
$.fn.visible = function(partial, hidden) {
var $t = $(this).eq(0),
t = $t.get(0),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height(),
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom,
clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)); };
$(window).scroll(function(event) {
$(".wew").each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
el.addClass("inview");
} else {
el.removeClass("inview");
}
});
});
答案 0 :(得分:0)
我在这里简化了你的代码,但主要区别在于我在顶部添加了一个阈值,并从底部阈值中减去了一个阈值。当您滚动时,您会注意到只有顶部或底部超过阈值的项目才能应用该类..
请注意,您可以通过更改50到100或您需要的任何内容来调整阈值:el.isWithinThreshold(50)
$.fn.isWithinThreshold = function(threshold) {
var $t = $(this).eq(0),
t = $t.get(0),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height()
return (_bottom <= viewBottom - threshold) && (_top >= threshold + viewTop);
};
$(window).scroll(function(event) {
$(".wew").each(function(i, el) {
var el = $(el);
if (el.isWithinThreshold(50)) {
el.addClass("inview");
} else {
el.removeClass("inview");
}
});
});
&#13;
.wew {
border: 1px solid black
}
.inview {
border: 5px solid black
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
<div class='wew'>stuff</div>
&#13;