【问题标题】:scrollIntoView - behavior is not working(JavaScript)scrollIntoView - 行为不起作用(JavaScript)
【发布时间】:2021-09-07 12:41:59
【问题描述】:

我知道在 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>

这就是所有需要的代码。

CODE PEN EXAMPLE

【问题讨论】:

  • it is suppose to go to but?嗯?请正确描述问题。此外,查看相应的 HTML 也会有所帮助

标签: javascript html css smooth-scrolling js-scrollintoview


【解决方案1】:

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

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

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

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

【讨论】:

  • 我明白你的意思,但这根本没有区别
  • 我已经编辑了你的笔并且它有效。请看codepen.io/vdloc/pen/xxrRorz
  • 你的锚标签选择器语法 (document.querySelectorAll("scroll:link")) 对我来说是新的,当我检查它时,它没有返回任何链接元素,所以我改变了选择器到 "a[class^=scroll]" 或 a[href^='#']。
  • 我不明白 a[href^='#'] 我把它写成 'scroll:link' 的原因是因为我有不同的按钮导致不同的页面,所以按钮必须有平滑滚动我给了一个滚动类,所以所有按钮都不能平滑滚动,即使我不知道这意味着什么非常感谢你
【解决方案2】:

也添加这些附加属性以使其工作

element.scrollIntoView({
  behavior: 'smooth',
  block: 'start',
  inline: 'nearest'
});

编辑:在您的情况下,您只需将以下 css 放入您的主样式文件中,因为滚动不是由您编写的 javascript 代码发生的,它是由于标签的 href 而发生的。你甚至可以删除 javascript 代码

* {
    scroll-behavior: smooth
 }

【讨论】:

  • 这个不行,我以前试过,现在又试了,还是不行
  • 所需的一切都在那里
  • 根据您的情况更新了答案,希望这能帮助您了解您所面临的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 2020-01-09
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多