Javascript / jQuery:动画发生两次?

时间:2014-10-16 09:32:16

标签: javascript jquery

我正在写一个简单的函数,你传递一个jQuery对象,然后它应该变成红色,并淡出回原来的颜色。

这是:

function flash_cell(target) {
  var original_background_color = target.css('background-color');

  target.css("background-color", "#d79795");
  target.animate({ "background-color": original_background_color}, 1500);
}

相当简单。还是......?因为当我运行该功能时,它会按照它应该做的那样......然后它会变成红色。再次。为什么???

1 个答案:

答案 0 :(得分:2)

您的脚本应该如果

  • 您正在使用文档就绪 $(function(){ /*Code here*/ }); // Dom is ready
  • 您使用 jQuery UI (否则背景动画将不会发生)
  • 您正在将 fn 传递给 jQuery对象元素参数flash_cell( $("#el") )

$(function(){

    function flash_cell(target) {
      var original_background_color = target.css('background-color');

      target.css("background-color", "#d79795");
      target.animate({ "background-color": original_background_color}, 1500);
    }

    // ___________________________

    var $div = $('div');

    flash_cell($div);         // Do it when DOM is ready

    $div.click(function(){
      flash_cell( $(this) );  // Do it on click
    });

    // No other flashes will occur (unless you click it ;) ).

});

<强> demo

关于元素再次变红...可能你在不同的地方调用你的函数,很难说你发布的代码。详细探索,你会发现你的错误。

相关问题