滚动功能IE出错

Error on scroll function IE

本文关键字:出错 IE 功能 滚动      更新时间:2023-09-26

我在IE的滚动功能有问题。

下面的代码http://jsfiddle.net/VdNQL/

这里的问题是,当你点击链接(顶部)它会去到特定的地方,但之前它只是在它走了一次之后。在Firefox和chrome中都能看到。我认为问题出在jquery上。这是我的jquery。

        $(document).ready(function(){            
        $(window).scroll(function(){
            if ($(this).scrollTop() > 50) {
                $('div').addClass("k");
            } else {
                $('div').removeClass("k");
            }
        }); 
   $("a").bind('click', function() {
    var hash = $(this).attr("href");
    $('html, body').animate({ scrollTop: $(hash).position().top - 50 }, 1000);
  });
  });

谢谢你的建议。

.preventDefault()停止link元素的默认动作

$("a").bind('click', function(ev) {
    ev.preventDefault();
    var hash = $(this).attr("href");
    $('html, body').animate({ scrollTop: $(hash).position().top - 50 }, 1000);
});
http://jsfiddle.net/VdNQL/2/

这是因为你的href click也试图在同一时间工作。防止默认的href行为。这消除了抖动行为。

$("a").bind('click', function(event) {
    event.preventDefault();
    var hash = $(this).attr("href");
    $('html, body').animate({ scrollTop: $(hash).position().top - 50 }, 1000);
});

在您的代码中,当窗口滚动顶部大于50时,将类k添加到div中。在类k中,您将top设置为1px。所以你的脚本将顶部设置为1px,然后开始动画。