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

时间:2013-01-03 20:12:55

标签: jquery internet-explorer firefox offset

所以我使用的是Cedric Dugas的Anchor Slider。会发生什么事情是有人点击一个链接,它会将页面向下滚动到与链接相同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像素以上,然后突然转移到正常停止的位置。

任何人都有任何关于为什么会这样的想法?

谢谢!

1 个答案:

答案 0 :(得分: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);
});

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