window.scrollTo 不滚动到提供的 id [英] window.scrollTo not scrolling to provided id
问题描述
我正在处理单个文档文件.我想滚动到 id="projectpage" 所需的部分当 id="about" 的锚点时被点击.
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">
我尝试使用
$('a#about').click(function(){
$(window).scrollTo(0, document.getElementById('projectpage').offsetTop);
});
甚至
$('#about').click(function(){
$(window).scrollTo(0, document.getElementById('projectpage').offsetTop);
});
但没有任何效果.
当我单击 id="about" 的锚点时,它只会将我重定向到 index.html(包含所有文档的主 HTML)文件本身,而不是转到 id="projectpage" 的 offsetTop.
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".
推荐答案
我用 scrollIntoView()
为你做了一个小例子.此外,请考虑需要 event.preventDefault()
禁用点击标签 a
的默认功能.
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
.
另外,scrollIntoView()
有一个带动画过渡效果的参数:
In addition, scrollIntoView()
has a parameter with an animation transition effect:
behavior: "smooth"
注意:由于您使用的是 jquery
,我认为将其转换为如下元素没有意义:
Note: since you are using jquery
, I see no point in casting to an element like:
document.getElementById('aboutpage')
上诉,如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>
这篇关于window.scrollTo 不滚动到提供的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!