簡體   English   中英

使用 jQuery 滾動到錨點僅在您不在當前頁面上時才有效

[英]Scroll to anchor with jQuery only works when your not on the current page

問題是,當我單擊具有同一頁面上的主題標簽的鏈接時,動畫滾動不起作用。 動畫滾動僅在您不在當前頁面時有效。

網址看起來像這樣:

  • website.com/about#people,
  • website.com/about#contact

因此,假設您在“關於頁面”上並單擊其中任何一個鏈接,向下滾動動畫將不起作用,但假設您在主頁上並單擊這些鏈接中的任何一個,動畫確實有效。

不幸的是,我無法在代碼片段上復制該問題,但我使用的是相同的js代碼。 奇怪的是,在此代碼段中,即使您在同一頁面上,動畫也能正常工作。 不,我在控制台上沒有收到任何錯誤。

謝謝!

 $('nav a[href^="#"]').click(function(){ $('html, body').animate({ scrollTop: $(this.hash).offset().top }, 400); return false; });
 #topSection{ background: red; height: 400px; } #middleSection{ background: blue; height: 400px; } #lastSection{ background: black; height: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li><a href="#topSection">Top Section</a></li> <li><a href="#middleSection">Middle Section</a></li> <li><a href="#lastSection">Last Section</a></li> </ul> </nav> <div id="topSection"> </div> <div id="middleSection"> </div> <div id="lastSection"> </div>

當您訪問帶有散列的頁面時,滾動到散列不起作用的原因是您的代碼僅在單擊鏈接時調用。 為了進一步詳細說明我的評論,因此您還需要在加載頁面時調用相同的代碼。

這可以通過簡單地將點擊處理程序中的所有邏輯抽象成一個可以獨立於點擊事件調用的函數來完成:

function smoothScrollTo(hash) {
  if (!hash)
    return;

  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 400);
}

$(function() {
  // Smooth scrolling when the page is loaded
  smoothScrollTo(window.location.hash);

  // Smooth scrolling when a link is clicked
  $('nav a[href^="#"]').click(function() {
    smoothScrollTo(this.hash)
    return false;
  });
});

請參閱下面的概念驗證:

 function smoothScrollTo(hash) { if (!hash) return; $('html, body').animate({ scrollTop: $(hash).offset().top }, 400); } $(function() { // Smooth scrolling when the page is loaded smoothScrollTo(window.location.hash); // Smooth scrolling when a link is clicked $('nav a[href^="#"]').click(function() { smoothScrollTo(this.hash) return false; }); });
 #topSection { background: red; height: 400px; } #middleSection { background: blue; height: 400px; } #lastSection { background: black; height: 400px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li><a href="#topSection">Top Section</a></li> <li><a href="#middleSection">Middle Section</a></li> <li><a href="#lastSection">Last Section</a></li> </ul> </nav> <div id="topSection"> </div> <div id="middleSection"> </div> <div id="lastSection"> </div>

暫無
暫無

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

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