2

私の質問は、.offset() を使用してブラウザーの y 位置を見つけることです。ある時点で、div にクラスを追加したいのですが、yourkarma.comのようなものを作成したいと考えています(「IT の動力源」セクションを参照してください)。

$(document).ready(function() {
    $(window).scroll(function (event) {
    // what the y position of the scroll is
    var z = '150';
    var x = $('#thisdiv').offset().top - z;
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= x) {
      // if so, ad the fixed class
      $('#thisdiv').addClass('red');
    }
  });
})

私は正しい道を進んでいますか?私は z=150 を使用し、それを X に差し引くのはちょっと安上がりな方法だと思います。もっと良いものを作る方法はありますか?

4

1 に答える 1

1

それは安くはありませんが、より明確で効率的な方法は次のとおりです。

var $thisdiv = $('#thisdiv');
var thisdiv_top = $thisdiv.offset().top - 150;
var thisdiv_flag = false;

$(window).scroll(function (event) {
    if(thisdiv_flag) return;

    // what the y position of the scroll is
    var y = $(window).scrollTop();

    // whether that's below the form
    if (y >= thisdiv_top) {
        // if so, ad the fixed class
        $thisdiv.addClass('red');
        thisdiv_flag = true;
    }
});

なぜ-150なのかはよくわかりません。要素が表示される前に少し早くトリガーされると思います。しかし、このコードはもう少し効率的です。div の jQuery オブジェクトをキャッシュし、フラグを設定して、イベントが再度発生しないようにします。また、ユーザーがスクロールするたびに同じオフセット計算を行う必要がなくなります。

お役に立てれば。

于 2013-03-14T02:35:02.270 に答える