jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了事件 – jQuery能否确定当前用户浏览器视图中的哪些div?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有可能确定当前在浏览器视图中的哪个div,然后在发生这种情况时触发事件?基本上,我有一个网站,在一个页面上有5-6个部分,我想根据浏览器当前查看的部分来激活事件.我知道我们可以使用hrefs中的#tag直接链接页面的位置,但这是否可以确定哪个目前在浏览器的主视图中?

解决方法

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

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

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

updatE
添加jsbin以查看它的实际效果.请享用

本图文内容来源于网友网络收集整理提供,作为学习参使用,版权属于原作者。

大佬总结

以上是大佬教程为你收集整理的事件 – jQuery能否确定当前用户浏览器视图中的哪些div?全部内容,希望文章能够帮你解决事件 – jQuery能否确定当前用户浏览器视图中的哪些div?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。