javascript - scrollIntoView - 行为不起作用(JavaScript)
问题描述
我知道 stackOverflow 上还有其他问题与相同的问题(2016 年及更早版本),但我都经历了它们,但它们并没有解决我的问题。
滚动到视图中,当我单击按钮时,页面会转到它应该转到的特定部分,但行为属性不起作用。
const alllinks = document.querySelectorAll("scroll:link");
alllinks.forEach(function (link) {
link.addEventListener("click", function (e) {
e.preventDefault();
const href = link.getAttribute("href");
// Scroll to top
if (href === "#") {
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
//Scroll to other links
else if (href !== "#" && href.startsWith("#")) {
document.getElementById(href).scrollIntoView({
behavior: `smooth`,
});
}
});
});
以下是 html 对所有部分的看法。(这里仅以一节为例)
<a class="scroll nav-list--item btn" href="#how">How it works</a>
<section class="section-more container" id='how'>...</section>
这就是所有需要的代码。
解决方案
getElementById的参数必须是元素 id 值并且不包含“#”。
document.getElementById(href).scrollIntoView({
behavior: `smooth`,
});
这段代码会抛出 TypeError,因为 document.getElementById(href) with href = "#how" 将返回 undefined,所以当您在链接中单击时,滚动行为只是链接的默认行为。可能您可以像这样更正它:
document.getElementById(href.slice(1)).scrollIntoView({
behavior: `smooth`,
});
推荐阅读
- r - Plumber API 接受用于 API 评分的图像
- python - 如何获取对象是其实例的所有类的列表?
- amazon-pay - 亚马逊支付沙盒重定向 url 更新
- artifactory - 将现有 Artifactory OSS 安装迁移到现有 Artifactory PRO 安装
- python - 我希望我的函数在 python 中接受大小写字母
- c# - 防止在错误时执行下一个 ValidationAttributes
- internet-explorer-11 - [BHO][IE11] 捕获事件 newtab
- python - 通过 python3 中连接集群的多数投票进行标记
- javascript - Javascript Moment.js 将时间从上午更改为下午
- react-native - 反应本机屏幕配置失败