javascript - jQuery 平滑滚动以锚定在不同页面上

标签 javascript jquery html

如果一个元素链接到同一页面上的 anchor ,我的 jQuery 平滑滚动可以工作,但当链接到不同页面上的 anchor 时,它不会平滑滚动。

我的 jQuery 脚本有任何明显的问题吗?

<script>
jQuery(function($) {

    // //////////////////////// Smooth Scroll To Specific Element On Page ////////////////////////

    $(document).ready(function() {
        $('a[href^="#"]').not('.carousel-control-prev').not('.carousel-control-next').bind('click.smoothscroll', function(e) {
            e.preventDefault();

            var hash = this.hash;

            jQuery('html, body').animate({
                scrollTop: jQuery(hash).offset().top - 65
            }, 1500, function(){});
        });
    });

    //////////////////////// Smooth Scroll To Specific Element On Different Page ////////////////////////

    $(document).ready(function(){
        var urlHash = window.location.href.split("#")[1] || false;
        if (urlHash.length > 0)
            $('html,body').animate({
                scrollTop: $('#' + urlHash).offset().top - 60
            }, 2500);
    });

});
</script>

最佳答案

以下示例代码提供了所需的功能:

$(document).ready(function () {
    var urlHash = window.location.href.split("#")[1];
    if (urlHash &&  $('#' + urlHash).length )
          $('html,body').animate({
              scrollTop: $('#' + urlHash).offset().top - 60
          }, 2500);
});

请注意,如果该 URL 已被访问,浏览器将自动跳转到哈希而不显示动画,然后要重现我们需要清除缓存的行为,那么解决方法可以是实现清除缓存功能,如果我们打算再次显示动画。

关于javascript - jQuery 平滑滚动以锚定在不同页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878041/

相关文章:

javascript - 使用文本框中的值到按钮形成操作上的变量

javascript - getElementById().appendChild() 拒绝工作!

javascript - 在使用 D3.js fork 3D Force-Directed Graph 创建的 2D 图形上的鼠标左键上添加鼠标平移

jquery - 视频.JS : How do I add my own custom play and pause button in the middle of the video-container?

JQuery - 将 CSS 更改应用于类的单个元素

css - 垂直居中加载微调器覆盖

javascript - JSON:已收到响应但无法在 jQuery 中显示它

jquery - 用户在字段中键入时如何将文本字段数据转换为大写?

html - Bootstrap 网站 jumbotron 图像缩放

html - 使用 HTML 中的类居中彩色字母文本