是否可以确定当前在浏览器 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/