在执行动画之前,jQuery页面会跳转到顶部

时间:2014-01-22 20:33:01

标签: javascript jquery scroll page-jump

我正在尝试为我的网站制作一个幻灯片动画。核心功能就在那里,但我遇到了问题,每当我点击一个元素时(当页面不在顶部时)页面跳到顶部,返回,然后按预期制作动画。我研究了最后几天,但我的问题似乎是独特的,所以我决定问这个问题。这就是我所拥有的:

<div class="content">
    <div class="inner_content">
        <div id="first" class="first"></div>
        <div id="second" class="second"></div>
        <div id="third" class="third"></div>
    </div>
</div>

这个想法是点击一个div(第一个,第二个,第三个),然后由于导航栏的原因,从顶部向上滚动130 px。这是我的jQuery:

<script>
    $( "div.first").click(function(){
        $("html, body").animate({
            "scrollTop": $("div.first").offset().top -130 
        }, 500);
        $( "div.second").click(function(){
            $("html, body").animate({
                "scrollTop": $("div.first").offset().top -130 
            }, 500);
            $( "div.third").click(function(){
                $("html, body").animate({
                    "scrollTop": $("div.first").offset().top -130 
                }, 500);
</script>

问题如上所述。页面快速跳转到页面顶部,然后返回到上一个位置。之后,上下滑动动画非常干净流畅。我真的不知道问题出在哪里。我希望有人可以帮助我。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您错过了一些结束括号。

$(document).ready(function () {
    $("div.first").click(function () {
        $("html, body").animate({
            "scrollTop": $("div.first").offset().top - 130
        }, 500);
    });
    $("div.second").click(function () {
        $("html, body").animate({
            "scrollTop": $("div.first").offset().top - 130
        }, 500);
    });
    $("div.third").click(function () {
        $("html, body").animate({
            "scrollTop": $("div.first").offset().top - 130
        }, 500);
    });
});

此外,我确实注意到您在div.click上触发动画,但如果您在anchor上执行此操作,则可以使用event.preventDefault();