【问题标题】:Function to be called once div hits top of viewport windowdiv 到达视口窗口顶部时调用的函数
【发布时间】:2017-05-23 12:27:10
【问题描述】:
想知道你是否可以看看下面的代码。
我希望在滚动时红色框的顶部碰到视口的顶部时调用一个函数。
JS 小提琴:http://jsfiddle.net/ay5ttmLk/
HTML
<div class="test" style="height:100px;width:70px;">
sadfsadf
saf
sadf
saf
s
af
saf
saf
sadf
sadfsafsafsaf
</div>
<div class="test" style="height:100px;width:70px;">
sadfsadf
saf
sadf
saf
s
af
saf
saf
sadf
sadfsafsafsaf
sadfsaf
sadfsafsadf
</div>
CSS
.test {margin-top: 500px;
margin-bottom: 1000px;
background-color: red;}
JS
var el = $('.test');
el.on('scroll', function(){
if(el.scrollTop() == 0){alert("hit the top")}
});
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
检查this fiddle。
我已添加代码以在 .test div 到达顶部(多次)时发出警报。如果您只需要调用一次警报/某些代码,则需要删除 else 部分。
下面是代码。
$(document).ready(function() {
$('.test').attr("attop", false);
var lastScrollTop = 0;
$(window).on('scroll', function() {
var windowScrollTop = $(this).scrollTop();
if (windowScrollTop > lastScrollTop) {
var currentDiv = $('.test[attop="false"]:first');
if (currentDiv && currentDiv.length > 0) {
if (windowScrollTop >= currentDiv.offset().top) {
currentDiv.attr('attop', true);
alert('reached top');
}
}
} else {//this part needs to be removed to call only once
var currentTopDivs = $('.test[attop="true"]');
if (currentTopDivs && currentTopDivs.length > 0) {
$.each(currentTopDivs,function(i,elem){
if (windowScrollTop <= $(elem).offset().top) {
$(elem).attr('attop', false);
}
});
}
}
lastScrollTop = windowScrollTop;
});
});
希望这是您想要实现的目标。
【解决方案2】:
我认为没有办法检查顶部视口(有文档顶部)。但是,您可以进行手动测试来检查它:
$(window).on('scroll', function() {
var topViewPort = $(window).scrollTop();
// You have 2 problems here
// - Your el is an array with two elements. You have to specify which one you want to check or add extra condition
// - scrollTop on the element doesn't mean anything. You need to use offset().top to get the data
var topElement = $(".test").eq(0).offset().top;
// Do small check (gap length < 100?) to consider it on top.
}