【问题标题】:Smooth Scrolling anchor with offset (jquery)带有偏移量的平滑滚动锚点(jquery)
【发布时间】:2019-07-16 23:20:02
【问题描述】:

我正在使用以下代码为我的网站上的锚点添加平滑滚动。 因为我有一个粘性标题 id 想用 200px 来抵消这个

$('a[href*="#"]:not([href="#"])').click(function() {
    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) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});

【问题讨论】:

    标签: javascript jquery scroll anchor-scroll


    【解决方案1】:

    尝试在 scrollTop 动画中添加或删除一个值

    $('a[href*="#"]:not([href="#"])').click(function() {
        var offset = -200; // <-- change the value here
        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) {
                $('html, body').animate({
                    scrollTop: target.offset().top + offset
                }, 1000);
                return false;
            }
        }
    });
    

    【讨论】:

    • 此解决方案运行良好,但不会将 URL 更改为 #anchor。所以用户不能直接链接到带有锚点的url。
    【解决方案2】:

    一个没有哈希的更简单的例子是:

    $(document).on('click', 'a[href^="#"]', function (event) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top + -200
        }, 1000);
    });
    

    【讨论】:

    • 像魅力一样工作!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多