1

divスクロールの問題に対する非常に高速な解決策を探しています。

フォーラムの投稿のように、上下に配置された一連のdivがあります。ページが上下にスクロールするときに、それらのdivの1つがページ上の任意のポイントにヒットしたときを知りたいです。

私が試した1つの方法は、各アイテムにonScrollイベントを追加することでしたが、アイテムの数が増えると、ページは実際に遅れ始めます。

誰かがこれを行うためのより効率的な方法を知っていますか?ありがとう/w

4

2 に答える 2

3

まあ、私はこれらすべてに不慣れなので、誰かが私を修正する必要があるかもしれません:)

私は提案します

  • キャッシュ投稿の位置
  • 現在のcaсhe
  • 二分探索を使用する

デモ: 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にバインドするのではなく、window代わりにバインドする必要があります。次に、要素のオフセット値を簡単に計算して、divの1つがターゲットポイントとオーバーラップしているかどうかを確認する必要があります。

$(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 に答える