繁体   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