【问题标题】:Jquery: Smooth Scrolling script not workingJquery:平滑滚动脚本不起作用
【发布时间】:2024-01-01 21:35:01
【问题描述】:

不知何故,我不知道如何让这个平滑滚动 Jquery 脚本为我工作。

第一个 console.log 确实返回“测试”,第二个在我单击链接后什么也不返回。我正在通过 Prepros 处理 Localhost,这可能与脚本不起作用有关吗?代码也不会返回任何错误。

jQuery Code Snippets: Smooth Scrolling

<script src="scripts/dist/jquery-3.3.1.js"></script>

var local = local || {};
local.Link = (function() {
var link = {};

console.log("Test");

function linkSmoothScroll() {
    $('a[href*="#"]:not([href="#"])').click(function() {

        console.log("Test-inside");
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length ? $target : $('[name=' + this.hash.slice(1) + ']');

            if ($target.length) {
                var baseMinScrollTime = 200,
                    baseMaxScrollTime = 500;

                var docHeight = $(document).height(),
                    triggerTop = $(this).offset().top,
                    targetTop = $target.offset().top;

                var scrollProportion = (targetTop - triggerTop) / docHeight,
                    relativeTime = ((baseMaxScrollTime - baseMinScrollTime) * scrollProportion) + baseMinScrollTime,
                    // Create inverse relationship (quicker the further we scroll)
                    scrollTime = -1 * (1 - relativeTime);

                $('html, body').animate({
                    scrollTop: targetTop - 10
                }, scrollTime);
                return false;
            }
        }
    });
}

linkSmoothScroll();

return self;

})();

【问题讨论】:

    标签: jquery href smooth-scrolling


    【解决方案1】:

    你可以简单地通过动画滚动和使用一个额外的 CSS 属性来做到这一点。

    $("html, body").animate({ scrollTop: "0" }
    
    
    
    html {
        scroll-behavior: smooth;
    }
    

    【讨论】: