【问题标题】:How to not showing the #id in URL with cferdinandi/smooth-scroll如何不使用 cferdinandi/smooth-scroll 在 URL 中显示 #id
【发布时间】:2019-06-11 13:48:01
【问题描述】:

我正在使用 cferdinandi 的 smooth-scroll 包,但无法弄清楚如何使用不同的选择器而不是 ID,因此它不会显示在 URL 中。 例如,

我想要的是:example.com,而不是:example.com/#1

我所做的是将id 插入到我想要滚动到的div,并将相同的id 放入href<a> 元素中。

<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth- scroll@15.0.0/dist/smooth-scroll.polyfills.min.js"></script>
<script>
  const scroll = new SmoothScroll('a[href*="#"]', {
    speed: 800
  });
</script>

...
<a href="#1">About</a>
...


...
<section id="1">
  This is section about
</section>
...

它具有功能,只是我试图通过不显示 id 来使 URL 更好。

【问题讨论】:

标签: javascript css


【解决方案1】:

我不知道为什么锚 url 如此困扰你。当人们想要在您的网站上分享特定内容时,它会很有帮助。

但是如果你真的想要一个干净的方法来做,试试这个方法:

function goto(id) {
  document.getElementById(id).scrollIntoView();
}
html {
  /* You don't need any library to achieve smooth scroll */
  scroll-behavior: smooth;
}
<!-- polyfill for scroll-behavior: smooth; -->
<script src="https://cdn.jsdelivr.net/npm/scroll-behavior-polyfill@2/dist/index.min.js"></script>

<a href="javascript: void(0)" onclick="goto('1')">Go to 1</a>
<a href="javascript: void(0)" onclick="goto('2')">Go to 2</a>
<a href="javascript: void(0)" onclick="goto('3')">Go to 3</a>
<a href="javascript: void(0)" onclick="goto('4')">Go to 4</a>
<a href="javascript: void(0)" onclick="goto('5')">Go to 5</a>

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<label id="1">One</label>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<label id="2">Two</label>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<label id="3">Three</label>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<label id="4">Four</label>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<label id="5">Five</label>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多