jquery - jQuery 可以确定哪些 div 当前位于用户的浏览器 View 中吗?

标签 jquery events jquery-events

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

最佳答案

是的,你可以做到。 其背后的基本思想是观察滚动并确定用户关注的是哪个部分。 对此的一个很好的猜测通常是位于视口(viewport)顶部旁边的部分:

$(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 看到一个非常好的示例。

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

更新 添加了jsbin看看它的实际效果。享受吧;)

关于jquery - jQuery 可以确定哪些 div 当前位于用户的浏览器 View 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9251772/

相关文章:

angular - ClipboardEvent 在 IE11 中未定义

javascript - 如何通过 jQuery 删除值中的反斜杠?

javascript - 如何在用户开始输入时捕获事件?

jquery - 无法选择/jquery 来运行事件

javascript - 单击按钮时删除可拖动功能

javascript - 谷歌分析事件跟踪不起作用

java - 属性类如何在 Java 中为其 'parent' 类调用方法?

javascript - 如何将选定的索引值传递给更改函数

javascript - 我们如何在 javascript 中编写这个 $(this).parent ('p' )

javascript - 我必须打开模式对话框,点击功能(JQUERY 和 Bootstrap)不起作用