javascript - 点击时不会滚动
问题描述
我想让它滚动到我在导航栏中单击的部分,但是由于某种原因,当我单击时窗口不会滚动并且我没有收到任何错误,有人可以帮助我,想在 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',
});
}
})();
解决方案
您需要确保该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>
推荐阅读
- html - Bootstrap 4:左边的 Flexbox 图像和右边的文本
- sql - 仅在满足条件时执行许多脚本,而不通过 GO 语句中断 IF
- google-chrome - 在笔记本电脑上找不到带有 Chrome 的网络蓝牙设备
- javascript - onClick 有一个奇怪的行为
- python - 带有链接货币字段的 Django order_by 价格字段
- python - Python 从秒中获取小时分钟和天数
- spring-boot - Spring Boot oauth2 : Full authentication is required to access this resource
- regex - 正则表达式 - 从字符串开头或分隔符开头的分隔 IP 地址匹配,也允许通配符
- python - 我怎样才能使这个 for 循环结束而不阻止它拆分文本
- amazon-web-services - 通过 spark-submit 在 Docker 容器中运行应用程序时访问 AWS EMR 上的 S3