jQuery可以确定哪些div目前在用户的浏览器视图中?

mcr*_*ken 5 jquery events javascript-events

是否有可能确定当前在浏览器视图中的哪个div,然后在发生这种情况时触发事件?基本上,我有一个网站,在一个页面上有5-6个部分,我想根据浏览器当前查看的部分来激活事件.我知道我们可以使用hrefs中的#tag直接链接到页面的位置,但这是否可以确定哪个目前在浏览器的主视图中?

Tha*_*bas 6

是的,你可以这样做.其背后的基本思想是观看滚动并确定sections用户关注哪一个.对此的一个很好的猜测通常是视图顶部旁边的部分:

$(document).scroll(function() {
  var $this = $(this),
      scrollTop = $this.scrollTop(),
      // find the section next to the current scroll top
      sections = $(this).find('section'),
      topSection = null,
      minDist = Infinity;

  sections.each(function() {
    // calculate top and bottom offset of the section
    var top = $(this).offset().top,
        bottom = top + $(this).innerHeight(),
        // only use the minimum distance to the scroll top
        relativeDistance = Math.min(
          Math.abs(top - scrollTop), 
          Math.abs(bottom - scrollTop)
        );
    // in case the distance is smaller than
    // the previous one's replace it
    if (relativeDistance < minDist) {
      minDist = relativeDistance;
      topSection = this;
    }
  });

  // flip the 'top' class from current to now next one
  $('section.top').removeClass('top');
  $(topSection).addClass('top');    
});
Run Code Online (Sandbox Code Playgroud)

你可以在Play Webframework的主页上看到一个非常好的例子

如果这不是您想要的,您可以观察完整offsetposition任何元素,并使用$(window).innerWidth()或将其与当前视口进行比较$(window).innerHeight()

更新 添加了一个jsbin来查看它的运行情况.请享用 ;)