jQuery动画第一次跳过

时间:2012-09-07 04:41:02

标签: jquery animation hash scroll anchor

我有一个简单的脚本,可以在两个锚之间上下滑动页面:

$(document).ready(function() {

    $('a.switch').each(function() {
        var self = this;
        if(self.hash) {
            $(self).click(function() {
                $('html, body').stop().animate({
                    scrollTop: $(self.hash).offset().top
                }, 2000);
            });
         }
    });

});

然而,在打开页面后第一次调用此函数时,没有动画,它只是立即跳转到第二个锚点。然后恢复正常运作。

任何人都可以解释发生了什么以及如何解决它吗?

1 个答案:

答案 0 :(得分:1)

我认为您希望使用class name switch滚动页面加载的第一个元素,并且还想在每个元素上添加click事件,如果是,那么您可以尝试这个

$(document).ready(function() {
    var els=$('a.switch');
    $('html, body').stop().animate({
        scrollTop: $(els[0].hash).offset().top // els[0]=the first element, you can use the id too
    }, 2000);

    els.on('click', function(e) { // I've used 'on' and didn't use 'each'
        var self = this;
        if(self.hash) {    
            $('html, body').stop().animate({
                scrollTop: $(self.hash).offset().top
            }, 2000);
        }
    });
});​

DEMO