单击另一个页面的链接后如何平滑滚动到 id

新手上路,请多包涵

假设我在页面中有一个链接,

 <a href="https://example.com/#sample"><p>Click Me</a>

单击 click 会将您带到 href 属性中的链接。但是由于众神的工作方式,它会立即捕捉到该页面中的 id。

我想要发生的是页面不应该立即转到 id,而是从页面顶部开始,然后平滑滚动到 id。

在旁注中,粘性菜单挡住了路,当它捕捉到 id 时,它被菜单重叠(我希望它滚动的主要原因之一)。

jQuery 不是我的强项。

感谢任何可以提供帮助的人。

编辑 我认为我的措辞不正确。带有 a 标签的链接与其目标位于不同的页面上。例如:

主页有链接

<a href="https://example.com/anotherPage/#sample"><p>Click Me</a>

有一个名为 anotherPage 的页面,我想滚动它来处理它。

很抱歉没有让这不够详细。

感谢任何回复的人。

原文由 ace_01S 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 354
2 个回答

使用 jQuery 很简单,只需几行代码。

使用 $('a[href*=\\#]') 时,它仅/自动应用于所有锚点( <a> )和散列( # )。

 $(document).ready(function() {
    $('a[href*=\\#]').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
            scrollTop : $(this.hash).offset().top
        }, 500);
    });
});


更新

如果您想平滑滚动到 页面上的某个元素,请在 该页 面上包含以下代码:

 $(document).ready(function() {
    if (window.location.hash) {
        var hash = window.location.hash;
        $('html, body').animate({
            scrollTop :  $(hash).offset().top
        }, 500);
    };
});

它检查 URL 中是否有散列,如果有,它会平滑滚动到具有相应 id 的元素。


注意 1 :您可以通过更改 500 参数来改变速度。这是以毫秒为单位的动画时间。

注2 :也可以在 500 后面加一个参数,就是缓动类型。默认情况下它是 swing (类似于 CSS 的 ease-in-out )但你可以将它更改为 linear

原文由 Jeffrey Roosendaal 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 jQuery 的动画功能。

请参阅有关 w3 学校的示例: https ://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll

 $(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

原文由 user3692823 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题