是否可以在 URL 中隐藏 #section 名称?

问题描述 投票:0回答:1

当您单击导航栏中的链接时,它会滚动到链接到的页面部分。但是,它会在 URL 中留下#section_name。

我想知道是否有办法删除它,甚至只是摆脱

#
。它使 URL 看起来有点难看(IMO)。

html url
1个回答
0
投票

试试这个

document.getElementById('thing1').addEventListener('click', function(e) {
  e.preventDefault();
  const thing2 = document.getElementById('thing2');
  const thing2position = thing2.getBoundingClientRect();
  window.scrollTo({
    top: thing2position.top + window.scrollY,
    left: thing2position.left + window.scrollX,
    behavior: 'smooth'
  });
});
document.getElementById('thing2').addEventListener('click', function(e) {
  e.preventDefault();
  const thing1 = document.getElementById('thing1');
  const thing1position = thing1.getBoundingClientRect();
  window.scrollTo({
    top: thing1position.top + window.scrollY,
    left: thing1position.left + window.scrollX,
    behavior: 'smooth'
  });
});
#thing2{
  position: absolute;
  top: 1000px;
}
<body>
    <a href="#" id="thing1">first thing</a>
    <a href="#" id="thing2">second thing</a>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.