jquery .offset().top - 一定数量的像素(FF 和 IE 的问题)

标签 jquery internet-explorer firefox offset

所以我正在使用 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 像素处,然后突然向下移动到正常停止的位置。

有人知道为什么会发生这种情况吗?

谢谢!

最佳答案

这是浏览器的自然行为。当您访问包含片段的 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);
});

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

关于jquery .offset().top - 一定数量的像素(FF 和 IE 的问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14146469/

相关文章:

多个 var 项目上的 Jquery Click 事件

jquery - 网站架构问题

javascript - 单击复选框然后使用 jquery 删除验证

html - 下拉菜单在 Firefox/Chrome 中不起作用

javascript - 附加到 IE 中的正文问题

css - 找出浏览器版本何时偏离标记语言

javascript - 如何使用 javascript 测试 URL 是否是图像请求超时的有效图像?

c# - 如何使用 C# 连接到打开的 Internet Explorer 窗口?

Firefox 扩展 - 新选项卡 - 如何覆盖首选项?

javascript - 如何调整d3.js中箭头的方向?