如何检测元素何时滚动到视口中
我的网站底部有一个横幅广告。我正在使用Google Analytics事件来跟踪展示次数。问题是如果用户没有滚动到底部,他们将看不到横幅。因此,记录展示会导致不准确,除非我可以等到横幅在视口中。
I have a banner ad at the bottom of my site. I'm using Google Analytics events to keep track of impressions. The problem is that if the user doesn't scroll to the bottom, they won't see the banner. So recording an impression will cause inaccuracies unless I can wait until the banner is in the viewport.
我如何检测到我的横幅广告( id
#footer-banner
)是否已进入视口?我更喜欢只有在横幅的整个高度可见时才检测到它。
How would I detect that my banner ad (with an id
of #footer-banner
) has entered the viewport? I'd prefer if it only got detected once the entire height of the banner was visible.
使用jQuery,您可以:
Using jQuery, you can:
function isInView() {
var y = $('foot-banner').position().top;
var windowY = $(window).scrollTop();
return y > windowY && y < windowY + $(window).height();
}
然后在触发滚动事件时可以使用此函数:
Then this function can be used when a scroll event is triggered:
var impressionRecorded = false;
$(document).scroll(function() {
if (isInView() && !impressionRecorded) {
impressionRecorded = true;
// record impression
}
});