如何检测元素何时滚动到视口中 [英] How can I detect when an element scrolls into the viewport

查看:71
本文介绍了如何检测元素何时滚动到视口中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站底部有一个横幅广告。我正在使用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
  }
});

这篇关于如何检测元素何时滚动到视口中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆