1

HTMLドキュメントに添付されたアンカーリンクを追加できる次のスクリプトがあり.class、クリックするとWebページ上の位置にユーザーをスクロールします。

HTML:

<li class="about-scroll">About</li>

JavaScript:

$('.about-scroll').click(function () {
    $('body,html').animate({
        scrollTop: 646
    }, 1600);

    return false;
});

これは問題なく動作しますが、コンテンツが常に静的であるとは限らないため (ドロップダウン アコーディオン、レスポンシブ レイアウトなど)、ページ上の数値ではなく特定のタグ#divまたはタグにスクロールするにはどうすればよいでしょうか?section

例:

<div class="about">
    <h3>About</h3>
    ...
    ...
    ...
</div> <!-- end .about -->
4

2 に答える 2

3

an h3idたとえばヘッダーを指定します。次に、次を使用してクリック イベントを参照します。href="#header"

HTML

<h3 id="hi">HIIIIII</h3>
<a href="#hi">Scroll to Top</a>

jQuery

$('a').on('click', function (e) {
  e.preventDefault();                 // prevents default action of <a>
  var target = this.hash,             // gets the href of the <a>
      $target = $(target);            // puts it as a selector
  $('html, body').stop().animate({
    'scrollTop': $target.offset().top // scrolls to the top of the element clicked on
    }, 900, 'swing', function () {
    window.location.hash = target;
  });
});

フィドル

この機能の素晴らしいところは、再利用できることです。

于 2013-08-23T03:12:16.833 に答える
1

アニメーションがなくても問題ない場合は、移動したい要素に ID を指定し、href="#the_id_you_placed" で参照するだけという答えを使用できます。

アニメーションの場合は、引き続き ID を使用できますが、オフセットを見つけてそこにアニメーション化します。

$('.about-scroll').click(function () {
    $('body,html').animate({
        scrollTop: $('#the_id_you_placed').offset().top
    }, 1600);

    return false;
});
于 2013-08-23T03:19:29.423 に答える