首页 > 解决方案 > 点击时不会滚动

问题描述

我想让它滚动到我在导航栏中单击的部分,但是由于某种原因,当我单击时窗口不会滚动并且我没有收到任何错误,有人可以帮助我,想在 vanilla js 中完成此操作。

(function() {
            var scrollLinks = document.querySelectorAll('.scroll');
            for( var i = 0; i < scrollLinks.length; i++){
                scrollLinks[i].addEventListener('click', function(e){
                    e.preventDefault();
                    this_ = this;
                    var position = this_.getAttribute("href");

                    scrollIt(position);
                })
            }

            function scrollIt(position){
                console.log(document.querySelector(position).offsetTop)
                window.scrollTo({
                    top: document.querySelector(position).offsetTop,
                    left: 0,
                    behavior: 'smooth',
                });
            }


        })();

标签: javascript

解决方案


您需要确保该href属性具有前导#字符,因为您将其直接传递给.querySelector()方法,并且您的部分需要具有匹配id的 s。检查一下(你的 JavaScript 代码根本没有改变,我只添加了有效的 HTML):

(function() {
            var scrollLinks = document.querySelectorAll('.scroll');
            for( var i = 0; i < scrollLinks.length; i++){
                scrollLinks[i].addEventListener('click', function(e){
                    e.preventDefault();
                    this_ = this;
                    var location = this_.getAttribute("href");

                    scrollIt(location);
                })
            }

            function scrollIt(location){
                console.log(document.querySelector(location).offsetTop)
                window.scrollTo({
                    top: document.querySelector(location).offsetTop,
                    left: 0,
                    behavior: 'smooth',
                });
            }


        })();
html, body {

  height: 10000px;
}
#s1 {
  margin-top: 1000px;
}
<nav>
  <a class="scroll" href="#s1">s1</a>
</nav>
<section id="s1">Section 1</section>


推荐阅读