簡體   English   中英

單擊錨鏈接時應用平滑滾動(純 Javascript)

[英]Applying smooth scroll when clicking an anchor link (Pure Javascript)

我正在編寫代碼,當單擊錨鏈接時直接跳轉到頁面內的特定部分。

在這里,我想確保頁面根據通過錨鏈接單擊的特定部分向上或向下平滑滾動。

雖然關於堆棧溢出有很多答案討論了同樣的問題,但我只想通過編寫自己的代碼來測試我的技能。

我終於注意到我的代碼無法正常工作並且引發了很多錯誤

我希望有一個更好更好的解決方案來改進我的代碼

任何幫助將不勝感激

 function smoothScroll(){ let x = document.querySelectorAll('a[href*="#"]'); for(let i = 0; i < x.length; i++){ x[i].onclick=function(){ let target = this.hash; target.scrollIntoView({ behavior:'smooth', alignToTop:true, block:'start' }); } } } smoothScroll();
 .nav { position: relative; width: 100%; height: 60px; background-color: #111; }
 <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no"> <link type="text/css" href="/css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>smoothScroll</title> </head> <body> <div class="nav"> <a href="#section1" style="color:#fff;">Link1</a> <a href="#section2" style="color:#fff;padding-left:3rem;">Link2</a> <a href="#section3" style="color:#fff;padding-left:3rem;">Link3</a> </div> <div id="section1"onclick="myFunction();" style="margin:10px auto; width:400px;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> <div id="section2" style="margin:100px auto; width:400px;"> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> <div id="section3" style="margin:100px auto; width:400px;"> Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </div> </body> </html>

要修復錯誤,問題在於scrollIntoView的元素引用。

您提供的hash值作為不正確的元素參考。 您需要在使用 hash 值選擇元素后傳遞該元素。

let target = document.querySelector(this.hash); target.scrollIntoView()

function smoothScroll(){
    let x = document.querySelectorAll('a[href*="#"]');
    for(let i = 0; i < x.length ; i++){
      x[i].onclick=function(){
      let target = document.querySelector(this.hash);
      target.scrollIntoView({
      behavior:'smooth',
      alignToTop:true,
      block:'start'
          });
         }
       }
    }
    smoothScroll();

scrollIntoView()是跨瀏覽器兼容的。

參考: https://www.quirksmode.org/dom/w3c_cssom.html#t23

演示:

 function smoothScroll(){ let x = document.querySelectorAll('a[href*="#"]'); for(let i = 0; i < x.length; i++){ x[i].addEventListener('click', function(e){ e.preventDefault(); let target = document.querySelector(this.hash); target.scrollIntoView({ behavior:'smooth', alignToTop:true, block:'start' }); }); }; } smoothScroll();
 .nav { position: relative; width: 100%; height: 60px; background-color: #111; }
 <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no"> <link type="text/css" href="/css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>smoothScroll</title> </head> <body> <div class="nav"> <a href="#section1" style="color:#fff;">Link1</a> <a href="#section2" style="color:#fff;padding-left:3rem;">Link2</a> <a href="#section3" style="color:#fff;padding-left:3rem;">Link3</a> </div> <div id="section1"onclick="myFunction();" style="margin:10px auto; width:400px;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> <div id="section2" style="margin:100px auto; width:400px;"> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> <div id="section3" style="margin:100px auto; width:400px;"> Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </div> </body> </html>

 function smoothScroll(){ let x = document.querySelectorAll('a[href*="#"]'); for(let i = 0; i < x.length; i++){ x[i].addEventListener("click",function(){ this.scrollIntoView({ behavior:'smooth', alignToTop:true, block:'start' }); } ) } } smoothScroll();
 .nav { position: relative; width: 100%; height: 60px; background-color: #111; }
 <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no"> <link type="text/css" href="/css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>smoothScroll</title> </head> <body> <div class="nav"> <a href="#section1" style="color:#fff;">Link1</a> <a href="#section2" style="color:#fff;padding-left:3rem;">Link2</a> <a href="#section3" style="color:#fff;padding-left:3rem;">Link3</a> </div> <div id="section1"onclick="myFunction();" style="margin:10px auto; width:400px;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> <div id="section2" style="margin:100px auto; width:400px;"> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> <div id="section3" style="margin:100px auto; width:400px;"> Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </div> </body> </html>

暫無
暫無

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

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