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 回答