【问题标题】:jQuery page jumps to top before performing the animationjQuery 页面在执行动画之前跳转到顶部
【发布时间】:2014-03-11 01:37:10
【问题描述】:

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

<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>

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

【问题讨论】:

  • 看起来你的大括号/括号最后缺少一些
  • 这本身就可以正常工作jsfiddle.net/99W3P/1您的实际代码中必须有其他内容。你碰巧有一个&lt;a&gt; 和一个href 只是#jsfiddle.net/99W3P/2
  • @JamesMontagne Do you happen to have an &lt;a&gt; with an href of just #?。那是确切的点。非常感谢。两天前我自己发现但无法访问互联网将其标记为已解决。无论如何,谢谢。

标签: javascript jquery scroll page-jump


【解决方案1】:

您遗漏了一些右括号。

$(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(); 会很好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    相关资源
    最近更新 更多