簡體   English   中英

滾動到錨點

[英]Scroll to the anchor

碼:

function scroll_page(){

        var target = document.location.hash.replace("#","");
        var selector = 'div[id='+target+']';
        alert(selector);
        $('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
        return false;
    };

Сode在這里被稱為:

$(window).on('hashchange', function() {
  scroll_page();
    });

問題是,當您單擊鏈接時,該鏈接會急劇跳至該div,然后輕輕向上拉至其頂部。

試試下面的代碼,

$(function() {
      $('a[href*=#]:not([href=#])').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(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 140
        }, 1000);
        return false;
      }
    }
  });
});

如果您的鏈接中有錨點,例如<a href='#id'> ,那么它將在您的JavaScript之前觸發。 hashchange事件發生在滾動到錨點之后。

為防止這種情況,您需要綁定到click事件並阻止默認行為。

我會做這樣的事情。

HTML:

<a class="slow-scroll" href="#first">First</a>
<a class="slow-scroll" href="#second">First</a>
<a class="slow-scroll" href="#third">First</a>

JS:

$(".slow-scroll").on('click', function(e) {
    var target = $(this).attr("href").substr(1);
    var selector = 'div[id='+target+']';
    alert(selector);
    $('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
    e.preventDefault();
    return false;
});

這是JSFiddle演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM