window.scrollTo not scrolling to provided id

我的梦境 提交于 2021-02-10 06:14:31

问题


I am working on a single document file. I want to scroll to the desired section with id="projectpage" when an anchor with id="about" is clicked.

<a class="nav-link page-scroll"  href="" id="about">About Me</a>

<section id="aboutpage">

I tried using

$('a#about').click(function(){
    $(window).scrollTo(0, document.getElementById('projectpage').offsetTop);
    
  });

or even

$('#about').click(function(){
    $(window).scrollTo(0, document.getElementById('projectpage').offsetTop);
    
  });

but nothing works.

When I click on the anchor with id="about", it just redirects me to the index.html(the main HTML with all document) file itself rather than going to the offsetTop of id="projectpage".


回答1:


You need to prevent the default behavior of an anchor.... Using .preventDefault()

And replace $(window) for just window... You don't need jQuery to lookup for the window when you wish to apply a vanilla JS method on it.

$('#about').click(function(e) {
  e.preventDefault()
  window.scrollTo(0, document.getElementById('aboutpage').offsetTop);
});
section{
  height: 200px;
  border-top: 2px solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="nav-link page-scroll" href="" id="about">About Me</a>

<section id="somethingElse1">...</section>
<section id="somethingElse2">...</section>
<section id="somethingElse3">...</section>
<section id="aboutpage">About</section>
<section id="somethingElse4">...</section>
<section id="somethingElse5">...</section>



回答2:


I made a small example for you using scrollIntoView(). Also, take into account the need for event.preventDefault() to disable the default ability to click on the tag a.

In addition, scrollIntoView() has a parameter with an animation transition effect:

behavior: "smooth"

Note: since you are using jquery, I see no point in casting to an element like:

document.getElementById('aboutpage')

Appeal, as in jquery:

$("#aboutpage")[0]

$('a#about').click(function(event){
  event.preventDefault();
    $("#aboutpage")[0].scrollIntoView({
    behavior: "smooth"
  }); 
});
#first {
  width: 100%;
  height: 1000px;
  background-color: green;
}

#aboutpage {
  width: 100%;
  height: 1000px;
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="nav-link page-scroll"  href="" id="about">About Me</a>

<section id="first"></section>
<section id="aboutpage"></section>


来源:https://stackoverflow.com/questions/65385050/window-scrollto-not-scrolling-to-provided-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!