0

基本的にこれは私のページスクロールコードですが、各div要素の変数を使用していますが、ループ関数を使用してこのコードを最小化するにはどうすればよいですか?ありがとう!

var canvas = $('.div1');
var canvas2 = $('.div2');
var win = $(window);

win.bind('scroll', function(){

    //div1
    var pos = canvas.offset();
    var total = pos.top + canvas.height();
    win.top = win.scrollTop();
    var d = win.height() / 2 + win.top;

    if( pos.top < d && !(total < d) )
    $('.div1').addClass('active');  }
    else
    $('.div1').removeClass('active');

    //div2
    var pos2 = canvas2.offset();
    var total2 = pos2.top + canvas2.height();
    win.top = win.scrollTop();
    var d2 = win.height() / 2 + win.top;

    if( pos2.top < d2 && !(total2 < d2) ){ 
    $('.div2').addClass('active');}
    else
    $('.div2').removeClass('active');
});
4

1 に答える 1

3

.each反復と.toggleClass( className, switch )構文を使用した、これらの行の何か:

var $w = $(window),
    $canvases = $('.div1, .div2');

$w.scroll(function() {
    var d = $w.height() / 2 + $w.scrollTop();
    $canvases.each(function() {
        var $this = $(this),
            ptop = $this.offset().top,
            total = ptop + $this.height();
        $this.toggleClass('active', ptop < d && total >= d);
    });
});

ビューポートの垂直方向の中心を横切るオブジェクトactive内の要素にクラスを追加すると、正常に機能するはずです。$canvases

フィドル

于 2013-01-09T22:38:15.197 に答える