-3

タイトルの通り、このコードはより少ない行数で簡略化できると思います。誰かがこれで私を助けてくれますか?

    $('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

4 に答える 4

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)
});
于 2012-09-10T12:52:30.407 に答える
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);
});
于 2012-09-10T12:58:23.433 に答える
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;
    }
});
于 2012-09-10T12:58:41.070 に答える
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
);

このアプローチには手作業が必要ですが、将来のサイトで再利用可能なスニペットです。

于 2012-09-10T12:59:35.733 に答える