简体   繁体   English

单击锚链接时应用平滑滚动(纯 Javascript)

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

i'm writing the code, when the anchor link is clicked jump directcly to the specific section within the page.我正在编写代码,当单击锚链接时直接跳转到页面内的特定部分。

here i want to make sure that the page is smoothly scrolled either up or down according to the specific section clicked through the anchor link.在这里,我想确保页面根据通过锚链接单击的特定部分向上或向下平滑滚动。

although there is so many answers on stack overflow discussed the same issue but i just want to test my skills by writing my own code.虽然关于堆栈溢出有很多答案讨论了同样的问题,但我只想通过编写自己的代码来测试我的技能。

i finally notice that my code is not working and it throw many errors我终于注意到我的代码无法正常工作并且引发了很多错误

i hope there is a good and better solution to improve my code我希望有一个更好更好的解决方案来改进我的代码

Any help will be appreciated任何帮助将不胜感激

 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>

To fix the error, the issue is with the element reference for the scrollIntoView .要修复错误,问题在于scrollIntoView的元素引用。

You are providing the hash value as element reference which is incorrect.您提供的hash值作为不正确的元素参考。 You need to pass the element after selecting it with the hash value.您需要在使用 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() is cross-browser compatible. scrollIntoView()是跨浏览器兼容的。

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

DEMO:演示:

 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