使用每个或循环函数滚动jQuery页面

时间:2013-01-09 22:19:47

标签: jquery

所以基本上这是我的页面滚动代码,但我使用变量每个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');
});

1 个答案:

答案 0 :(得分: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对象内的元素应该可以正常工作。

Fiddle

相关问题