转到锚点而不更改网址

Dav*_*ith 6 javascript anchor window

在加载页面时,我希望它在#content不更改URL的情况下进行.

我以为我可以使用

window.location.hash = "content";
window.location.replace("#content", "");
Run Code Online (Sandbox Code Playgroud)

#content仍然存在于网址上.

有更好的方法吗?


编辑:

也试过了

window.location.hash = "content";
window.location.replace(window.location.toString().replace("#content", ""));
Run Code Online (Sandbox Code Playgroud)

但这会将浏览器发送到循环中.

Man*_*vin 6

转到或滚动到锚点指定的 div id,而不更改 url

尝试演示

function scrollSmoothTo(elementId) {
  var element = document.getElementById(elementId);
  element.scrollIntoView({
    block: 'start',
    behavior: 'smooth'
  });
}
#userdiv {
  margin-top: 200px;
  width: 200px;
  height: 400px;
  border: 1px solid red;
}

a {
  color: #337ab7;
  cursor: pointer;
}

a:hover {
  text-decoration: underline;
}
<a onclick="scrollSmoothTo('userdiv')">
  Scroll to userdiv
</a>

<div id="userdiv">
  Lorem ipsum this is a random text
</div>
Run Code Online (Sandbox Code Playgroud)


And*_*per 5

您可以找到具有该 id 的锚点的垂直位置,然后滚动到该位置。


小智 5

这是一个 10 年前的问题,但我在使用 Nextjs 时遇到了这个问题,并且希望顺利导航到较低的元素而不影响 url...Nextjs、Typescript。

const Anchor: React.FC = () => {
    const smoothScrollTo = e => {
          e.preventDefault();
          const element = document.getElementById('search');
          element.scrollIntoView({
              block: 'start',
              behavior: 'smooth' // smooth scroll
          })
    };

 return (
   <div>
      <a
        href=""
        onClick={smoothScrollTo}>
        Let's go!
      </a>
      <div id = "search">Take me here!</div>
   </div>
  )
};
Run Code Online (Sandbox Code Playgroud)

现在,在这里使用 refs 可能是最佳实践,但这正是我所需要的!我确信还可以进行其他改进!