如何使用JavaScript / jQuery跟踪在页面上滚动的div

时间:2013-01-16 01:13:33

标签: javascript jquery html scroll

我正在寻找一个快速解决div滚动问题的方法。

我有一组div,比如论坛帖子,它们是一个在另一个上面的。当页面向下或向上滚动时,我想知道其中一个div在页面上的任意点是什么时候。

我试过的一种方法是在每个项目中添加onScroll事件,但随着项目数量的增加,页面确实开始滞后。

任何人都知道更有效的方法吗?谢谢/ w

2 个答案:

答案 0 :(得分:2)

好吧,我对这一切都不熟悉,所以可能有人应该纠正我:)

我建议

  • 缓存帖子位置
  • caсhecurrent
  • 使用二进制搜索

演示:http://jsfiddle.net/zYe8M/

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

...

var posts = $(".post"), // our elements
    postsPos = [], // caсhe for positions
    postsCur = -1, // cache for current
    targetOffset = 50; // position from top of window where you want to make post current

// filling postsPos with positions
posts.each(function(){
    postsPos.push($(this).offset().top);
});

// on window scroll
$(window).bind("scroll", function(){
  // get target post number
  var targ = postsPos.binarySearch($(window).scrollTop() + targetOffset);
  // only if we scrolled to another post
  if (targ != postsCur) {
    // set new cur
    postsCur = targ;
    // moving cur class
    posts.removeClass("cur").eq(targ).addClass("cur");
  }
});

// binary search with little tuning on return to get nearest from bottom
Array.prototype.binarySearch = function(find) {
  var low = 0, high = this.length - 1,
      i, comparison;
  while (low <= high) {
    i = Math.floor((low + high) / 2);
    if (this[i] < find) { low = i + 1; continue; };
    if (this[i] > find) { high = i - 1; continue; };
    return i;
  }
  return this[i] > find ? i-1 : i;
};

答案 1 :(得分:0)

您不应该将滚动事件绑定到所有div,而只应绑定到window。然后,您应该通过简单计算元素偏移值来检查其中一个div是否与目标点重叠。

$(window).scroll(function(event)
{
    var isCaptured = capture();
    console.log(isCaptured);
});

function capture()
{
    var c = $('.box'); //this is the divs
    var t = $('#target'); //this is the target element
    var cPos = c.offset(); var tPos = t.offset();

    var overlapY = (cPos.top <= tPos.top + t.height() && cPos.top + c.height() >= tPos.top);
    var overlapX = (cPos.left <= tPos.left + t.width() && cPos.left + c.width() >= tPos.left);
    return overlapY && overlapX;
}

您可以将顶部和左侧(X,Y)偏移值直接传递给函数,而不是$('#target')元素。

嗯,这是一个肮脏的demonstration