2

私は次のスニペットを持っています

$('html,body').animate({scrollTop: $('#menu').offset().top}, 'slow');

リンクをクリックすると、ブラウザが#menudivの上部近くから表示されるようにしたいと思います。メニューの数ピクセル前に表示したいのですが。

どうすればこれを達成できますか?

offset()にpaddingTop:5を追加しましたが、これは望ましい結果ではありません。

4

2 に答える 2

16

から必要な量を差し引くだけです$('#menu').offset().top

$('html,body').animate({
    scrollTop: $('#menu').offset().top - 5 // or 10
}, 'slow');

これがフィドルです:http://jsfiddle.net/qVWuv/

于 2012-08-12T04:49:43.337 に答える
0

このコードはそれを修正しました。

$(function() {
      $('a').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(0) +']');
          if (target.length) {
            $('#content').animate({
              scrollTop: target.offset().top - 15
            }, 1000);
            return false;
          }
        }
      });
    });
于 2014-08-22T12:31:34.713 に答える