有没有可能确定哪个div当前在浏览器视图中,然后在发生时触发一个事件?基本上,我有一个网站,有5-6节都在一个页面上,我想激发事件取决于哪个部分是当前在浏览器上查看。我知道我们可以使用hrefs中的#标签直接链接到页面的位置,但这是否可以确定当前浏览器的主视图中是哪一个?
发布于 2012-02-13 03:59:11
是的,你可以这样做。这背后的基本思想是观察滚动,并确定用户关注的是哪一个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');
});你可以在Play Webframework's Homepage上看到一个很好的例子
如果这不是您想要的,您可以观察任何元素的完整offset或position,并使用$(window).innerWidth()或$(window).innerHeight()将其与当前视口进行比较
更新添加了一个jsbin来查看它的实际操作。享受;)
https://stackoverflow.com/questions/9251772
复制相似问题