首页 > 解决方案 > 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>

这就是所有需要的代码。

代码笔示例

标签: javascripthtmlcsssmooth-scrollingjs-scrollintoview

解决方案


getElementById的参数必须是元素 id 值并且不包含“#”。

 document.getElementById(href).scrollIntoView({
    behavior: `smooth`,
  });

这段代码会抛出 TypeError,因为 document.getElementById(href) with href = "#how" 将返回 undefined,所以当您在链接中单击时,滚动行为只是链接的默认行为。可能您可以像这样更正它:

document.getElementById(href.slice(1)).scrollIntoView({
    behavior: `smooth`,
  });

推荐阅读