Javascript/jQuery:动画发生两次

Javascript/jQuery: animation happening twice?

本文关键字:两次 jQuery 动画 Javascript      更新时间:2023-09-26

我正在编写一个简单的函数,向它传递一个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);
}

相当简单。还是?因为当我运行这个函数时,它会做它应该做的事……但后来它又变红了。为什么?

如果,您的脚本应该可以工作

  • 您正在使用文档就绪$(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 ;) ).
});

演示

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