jQuery 滚动和锚点初始位置

jQuery Scrolling & Anchor Initial Position

我正在使用这个 jQuery 平滑滚动代码:

$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 110)
        }, 1000, 'easeInOutExpo');
        event.preventDefault();
    });
});

我添加了 -110 偏移量以正确调整初始位置并且它工作正常,但每次我尝试从外部 link 访问锚点时,页面都会加载不同的偏移量值。请检查 http://www.iscreatividad.com/clientes/msl/servicios.html#serv-planificacion 以清楚地了解问题所在。如果您单击第一个图标,它会自动调整,您会看到它应该加载的方式。

在此先感谢您对此事的任何帮助。

您是在点击锚点时应用自定义滚动事件,而不是在加载时应用自定义滚动事件,因此当您使用 id 加载页面时,它会跳转到 id,这是默认行为。

$(document).ready(function () {

    var hash = window.location.hash;
    scrollToElem(hash);

    $('a.page-scroll').on('click', function (event) {
        var $anchor = $(this);
        var href = $anchor.attr('href');
        scrollToElem(href);
        event.preventDefault();
    });
});

var scrollToElem = function (hash) {
    var target = hash;
    $('html, body').stop().animate({
        scrollTop: ($(hash).offset().top - 110)
    }, 1000, 'easeInOutExpo');
};