2017-10-09 16 views
0

我想鏈接到'平滑滾動'相同頁面上的相應ID位置,並且與上部具有50px的距離來自這個位置的邊界。平滑的滾動工作得很好,它似乎也滾動到上邊界的確切位置。然後突然(幾毫秒後)頁面跳轉到上邊界(就好像'.offset()。top - 50'被某些東西覆蓋)。這裏會發生什麼?如何解決這個問題?儘管使用.offset(),平滑滾動到目標ID的網站跳轉到了屏幕上邊界。top - 50

$(function() { 
 
    // Add smooth scrolling to all links 
 
    $("a").on('click', function(event) { 
 
    // Make sure this.hash has a value before overriding default behavior 
 
    if (this.hash !== "") { 
 
     // Prevent default anchor click behavior 
 
     event.preventDefault(); 
 
     var hash = this.hash; 
 
     // 800 = milliseconds it takes to scroll; - 50 = vertical location 
 
     $('html, body').animate({ 
 
     scrollTop: $(hash).offset().top - 50 
 
     }, 800, function(){ 
 
     // Add hash (#) to URL when done scrolling (default click behavior) 
 
     window.location.hash = hash; 
 
     }); 
 
    } // End if 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a class="nav-link" href="#about">About</a> 
 
<div style="height: 2000px">testdiv before</div> 
 
<p style="height: 100px" id="about">target text to scroll and stop 50px above upper border</p> 
 
<div style="height: 2000px">testdiv after</div>

僅供參考我使用Chrome在1920px視寬,窗機。

+0

似乎發生由於'window.location.hash =散列;'。 https://jsfiddle.net/nd9ot0k3/1/ –

回答

0
// Add hash (#) to URL when done scrolling (default click behavior) 
    window.location.hash = hash; 

發生這種情況。一旦你把散列,如果你有元素#散列名的地方瀏覽器將滾動到它。它發生在回調您在這裏提供:

$('html, body').animate({ 
     scrollTop: $(hash).offset().top - 50 
     }, 800, function(){ 
     // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 
     }); 

唯一的辦法去解決那就是你的整個邏輯移到onhashchange事件,並從那裏觸發動畫。你需要做這樣的事情:

function handler(e){ 
    e.preventDefault(); 

    // scroll logic here 
} 

window.addEventListener("hashchange", handler, true); 

裏面的「處理程序」功能的「e」參數是參照事件對象,所以你可以得到的數據很多的出來。你將能夠解析window.location以獲得你需要去的確切的哈希。像$(window.location.hash)...而不是你的代碼。

入住這裏: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange https://developer.mozilla.org/en-US/docs/Web/API/Event