2

所以我正在使用 Cedric Dugas 的 Anchor Slider。发生的情况是有人单击链接并将页面向下滚动到与链接的 href 具有相同 ID 的元素......所有标准的东西。

但我想要发生的是让它在该 id 上方约 80 像素处停止......所以这就是我所拥有的。

$(document).ready(function() {
    $("a.anchorLink").anchorAnimate()
});

jQuery.fn.anchorAnimate = function(settings) {

    settings = jQuery.extend({
        speed : 500
    }, settings);   

    return this.each(function(){
        var caller = this
        $(caller).click(function (event) {  
            event.preventDefault()
            var locationHref = window.location.href
            var elementClick = $(caller).attr("href")

            var destination = $(elementClick).offset().top - 80;
            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
                window.location.hash = elementClick
            });
            return false;
        })
    })
};

这是将其向上移动 80 像素的代码行

var destination = $(elementClick).offset().top - 80;

问题是它在 webkit 浏览器中运行良好,但在 FF 和 IE 中,它会在 80 像素以上停止,然后突然向下移动到它通常停止的位置。

有人对为什么会发生这种情况有任何想法吗?

谢谢!

4

2 回答 2

1

这是浏览器的自然行为。当您访问包含片段的 url 时,浏览器会尝试导航到与片段对应的元素。因此https://stackoverflow.com/#h-recent-tags将导致浏览器向下(或向上)滚动到 ID 为h-recent-tags.

您的代码在发出以下命令时指示浏览器导航到该元素:

window.location.hash = elementClick;

这发生您的动画完成后,这就是为什么您会看到浏览器立即从原来的位置跳起来的原因。

为了获得您正在寻找的效果,需要采取不同的方法。在较新的浏览器中,您最好使用pushState,而不是直接篡改片段:

history.pushState(null, null, elementClick);

这将更新哈希,而不影响页面。但请注意,这只适用于现代浏览器。对于旧版本的 IE,您需要采取不同的方法。一种这样的方法是回退到使用该location.hash方法,但在滚动之前设置散列:

$(caller).on("click", function (event) {
    // Prevent default behavior of anchor
    event.preventDefault();

    // Get href value from anchor clicked
    var elementClick = $(caller).attr("href");

    // If the browser supports the History api, use it to update hash
    // Otherwise update hash before we animate the scrolling
    if (history && history.pushState) {
        history.pushState(null, null, elementClick);
    } else {
        window.location.hash = elementClick;
    }

    // Determine where 80px above target is
    var destination = $(elementClick).offset().top - 80;

    // Scroll to that new location
    $("html:not(:animated),body:not(:animated)").animate({
        scrollTop: destination
    }, settings.speed);
});

在较旧的浏览器中,这会导致立即转到目标位置,然后慢慢向上滚动以提供一些填充。

于 2013-01-03T20:36:21.180 回答
0

缺少许多分号。因此,某些浏览器可能会误读代码。将脚本粘贴到jshint以查看所有缺少的分号。

编辑

虽然上面是一个问题,但我正在改变我的答案。我敢打赌它实际上来自设置 window.location.hash 的行。这样做可能会导致某些浏览器跳转到文档中的该点,这将在动画完成后立即发生。

这可能是在不删除该行的情况下“修复”它的唯一方法:

var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
    window.location.hash = elementClick;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination - 80 }, settings.speed);
});

换句话说,一直向下滚动到锚点,然后设置哈希,然后向上滚动一点。您可以使用缓动使其看起来更平滑。

于 2013-01-03T20:25:25.590 回答