jQuery为什么代码用.animate()函数运行两次?

时间:2016-03-31 09:29:04

标签: jquery html css

在我目前的jQuery代码中,我希望能够动画到我的网页顶部并在之后下拉隐藏元素。问题是我使用if语句来检查这个元素是否被隐藏,但是我的代码在if语句中运行了两次,导致下拉列表在向下滑动后立即向上滑动。

当我运行以下代码时:

$("a#drop-user-box").click(function()
{
    $("html, body").animate({scrollTop: 0}, "slow", function()
    {
        alert("foo");
    });
    return false;
});

它会弹出警报,当我点击例如“确定”按钮,另一个警报弹出打开(意味着代码运行两次)。任何人都可以解释为什么会这样吗?

当我像这样添加警告时:

$("a#drop-user-box").click(function()
{
    alert("foo");
    //$("html, body").animate({scrollTop: 0}, "slow", function()
    //{

    //});
    //return false;
});

它将运行代码(在此(示例)情况下为警报)一次(但不是之后)。

JSFiddle

2 个答案:

答案 0 :(得分:5)

这是因为你动画了两个元素(body和html),因此有两个动画完整的回调。使用promise方法可以正常工作。

$("html, body").animate({scrollTop: 0}, "slow")
.promise().then(function() {
    alert("foo");
});

https://jsfiddle.net/719xffa5/3/

答案 1 :(得分:2)

是。由于选择器中传递了两个元素,因此回调函数会多次运行。

要解决您的问题,您可以使用whenthen方法:

$.when($('html,body').animate({scrollTop: 0},'slow'))
  .then(function() {
     alert('foo');
  });

demo

或者,您可以使用promise所述的here方法:

$('html, body').animate({scrollTop: 0}, 'slow')
.promise().then(function() {
    alert('foo');
});