我该如何组合这些代码?

时间:2012-09-10 12:48:49

标签: javascript jquery jquery-animate

正如标题所说,我认为这个代码可以用更少的行来简化。有人可以帮我这个吗?

    $('a[href=#over]').click(function(){
    $('html, body').animate({
        scrollTop: $("#over").offset().top - 100
    }, 2000);
});

$('a[href=#diensten]').click(function(){
    $('html, body').animate({
        scrollTop: $("#diensten").offset().top - 100
    }, 2000);
});

$('a[href=#portfolio]').click(function(){
    $('html, body').animate({
        scrollTop: $("#portfolio").offset().top - 100
    }, 2000);
});

$('a[href=#contact]').click(function(){
  $("html, body").animate({ scrollTop: $(document).height() }, 2000);
});

$('a[href=#top]').click(function(){
    $('html, body').animate({scrollTop:0}, 2000);
    return false;
});

我当时正在考虑if / elseif语句,但我有点卡在那里。你能看一下吗?

4 个答案:

答案 0 :(得分:5)

您可以使用锚点的href属性来按ID选择元素。

$('a').click(function(){
    var id = this.href;
    $('html, body').animate({
        scrollTop: $(id).offset().top - 100
    }, 2000);
});

$('a').click(function(e) {
    e.preventDefault();
    var id = this.href;
    var scroll = '';
    if (id === '#contact') {
       scroll =  $(document).height();
    } else if (id === '#top') {
       scroll = 0;
    } else {
       scroll = $(id).offset().top - 100;
    }
    $('html, body').animate({
           scrollTop: scroll
    }, 2000)
});

答案 1 :(得分:2)

未经测试。我只是将你的代码缩小(并进行了一些优化)。

$('a[href]').click(function(){
    var href = $(this).attr('href');
    var htmlbody = $('html,body');
    if( href == '#over' || href == '#diensten' || href == '#portfolio' )
    htmlbody.animate({ scrollTop: $(href).offset().top - 100 }, 2000);
    if( href == '#contact' )
    htmlbody.animate({ scrollTop: $(document).height() }, 2000);
    if( href == '#top' )
    htmlbody.animate({ scrollTop: 0 }, 2000);
});

答案 2 :(得分:2)

$('a').click(function(){

    var id = $(this).attr("href");

    if(id in {"#over": 1, "#diensten": 1, "#portfolio": 1}) {
      $('html, body').animate({ scrollTop: $(this).offset().top - 100 }, 2000);
    } 
    else if(id === "#contact") {
       $("html, body").animate({ scrollTop: $(document).height() }, 2000);
    } 
    else {
      $('html, body').animate({scrollTop:0}, 2000);
      return false;
    }
});

答案 3 :(得分:0)

由于您只是在整合流程,因此有无数的答案。但是,如果您需要微观管理目标,您可以执行以下操作:

function reusable_scroll_anchor( q_ids, q_off ) {
    for( var q_id in q_ids )(function(q_id) {
        $("a[href=#" + q_id + "]").click(function(){
            $('html, body').animate({
                scrollTop: $("#" + q_id).offset().top - q_off
            }, 2000);
        });
    })(q_ids[q_id]);
}

reusable_scroll_anchor(
    ['over', 'diensten', 'portfolio', 'contact', 'top' ], 
    100
);

虽然这种方法需要一些人工管理,但它是未来网站的可重复使用的代码段。

相关问题