1

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

我有一组 div,比如论坛帖子,它们一个一个叠放。当页面向下或向上滚动时,我想知道其中一个 div 何时命中页面上的任意点。

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

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

4

2 回答 2

3

好吧,我对这一切都很陌生,所以可能有人应该纠正我:)

我建议

  • 缓存帖子位置
  • 缓存当前
  • 使用二分查找

演示: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;
};
于 2013-01-16T02:07:49.753 回答
0

您不应该将滚动事件绑定到所有 div,而只能绑定到所有 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;
}

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

好吧,这是一个肮脏的演示

于 2013-01-16T02:44:26.593 回答