动画函数jquery运行两次

时间:2014-04-22 06:20:19

标签: javascript jquery html css

伙计我已经在这段代码上花了很长时间来摧毁我的大脑。对于我的生活,我无法弄清楚为什么每次点击链接时它会运行两次。任何人都可以看看我的代码并告诉我为什么要这样做?

<script type='text/javascript'>//<![CDATA[ 

$(function(){

function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollLeft: aTag.offset().left}, "slow", function() { console.log("test"); } );
};

$(".forward").click(function() {
    var div_name = $(this).attr("href");
    scrollToAnchor(div_name);
});

});//]]>

HTML

<div class="next">
    <span style="font-size:48px;"><a class="forward" href="#id2">&nbsp;></a></span>
</div>

CSS

.next{
    position:fixed;
    padding:10px;
    background: rgba(0,0,0, 0.6);
    top:48%;
    right:0;
    text-shadow: 1px 1px 1px #000;
    z-index:201;
}
.next a{
    text-decoration:none;
    color:white;
}
.next a:hover{
    text-decoration:none;
    color: red;
}

每次点击&#34;转发&#34;它应该只记录&#34;测试&#34;到控制台一次,但它记录了两次。

1 个答案:

答案 0 :(得分:3)

只是将我的评论添加为具有相同问题的其他人的答案:

$('html,body').animate({scrollLeft: aTag.offset().left}, "slow", function() { console.log("test"); } );
};

$('html,body')导致html标记和body标记被设置动画,因此动画似乎会运行两次。 只需将其更改为$('body')即可解决此问题。

相关问题