首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery可以确定哪些div当前在用户的浏览器视图中吗?

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

Stack Overflow用户
提问于 2012-02-13 03:09:34
回答 1查看 415关注 0票数 5

有没有可能确定哪个div当前在浏览器视图中,然后在发生时触发一个事件?基本上,我有一个网站,有5-6节都在一个页面上,我想激发事件取决于哪个部分是当前在浏览器上查看。我知道我们可以使用hrefs中的#标签直接链接到页面的位置,但这是否可以确定当前浏览器的主视图中是哪一个?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-13 03:59:11

是的,你可以这样做。这背后的基本思想是观察滚动,并确定用户关注的是哪一个sections。一个很好的猜测通常是位于视口顶部的部分:

代码语言:javascript
复制
$(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');    
});

你可以在Play Webframework's Homepage上看到一个很好的例子

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

更新添加了一个jsbin来查看它的实际操作。享受;)

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9251772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档