2

我有一个单页网站,其position: fixed;标题包含主导航。我正在使用这个插件通过主导航平滑滚动到每个部分。由于固定的标题,我需要设置标题的offsetwhich = height。使用此初始化一切正常:

$('.nav-main a').click(function(e) {
    e.preventDefault();
    var anchorLocation = $(this).attr('href');
    $.scrollTo(anchorLocation, 700, {
        offset: -86
    });
});

但是我需要在 URL 中包含部分 ID,例如http://domainname.com/#about 每个链接都包含在其中,所以我使用它:href<a href="#about">About</a>

$('.nav-main a').click(function(e) {
    e.preventDefault();
    var anchorLocation = $(this).attr('href');
    $.scrollTo(anchorLocation, 700, {
        offset: -86,
        onAfter: function() {
             window.location.hash = anchorLocation;
        }
    });
});

这样可以修复 URL,但会搞砸标题,因为有时它会在平滑滚动完成后消失,但如果您再次滚动并且它不起作用,那么它会重新出现在视图offset中。有任何想法吗?

编辑

有人发布了以下解决方案,但随后将其删除,但它的工作原理是不必使用插件,但offset只有在 IE 8/9 和 Firefox 的 Webkit 浏览器(Chrome、Safari)中有效,一旦滚动动画停止,它将兑现offset大约一毫秒,然后捕捉到视口的顶部。

var headerHeight = $('[role="banner"]').outerHeight() -1;

$('.nav-main a').click(function(e) {
    e.preventDefault();
    scrollToID($(this).attr('href'));
});

function scrollToID(ID){
    $('html, body').animate({
        scrollTop: $(ID).offset().top - headerHeight
    }, 700, function() {
        window.location.hash = ID;
    });
}
4

0 回答 0