不完美的Jquery动画时间

时间:2017-04-29 11:50:48

标签: javascript jquery css

var count = 0;
$(document).ready(function() {
  $("div").on("click", function() {
    $("#test").fadeOut(500);
    count++;
    $("#test").fadeIn(500);
    document.getElementById("test").innerHTML = count;
  });
});
div {
  background-color: gold;
  border: 2px solid goldenrod;
  border-radius: 7px;
  text-align: center;
  vertical-align: middle;
  font-family: Arial;
  font-size: 35px;
  width: 100px;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <div><span id="test">0</span></div>
</body>
</html>

我是Jquery的新手。在上面的代码中,div中的数字在点击时逐渐增加并逐渐淡出。我希望它能够工作,使现有数字先消失,然后显示下一个数字,而这里,数字首先变化,然后逐渐消失,在,这不是我想要它的工作方式。请运行代码段以查看问题。我的代码有什么问题或缺失?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

这是因为它需要fadeOut 500毫秒但count的增量并且分配立即发生。您可以使用fadeOut的回调complete来实现您的需求:

$("#test").fadeOut(500, function() { // the function will be called when the fadeOut is completed
    count++;                         // increment count
    this.textContent = count;        // assign it to this element (#test) textContent
}).fadeIn(500);                      // then fadeIn

var count = 0;
$(document).ready(function() {
  $("div").on("click", function() {
    $("#test").fadeOut(500, function() {
        count++;
        this.textContent = count;
    }).fadeIn(500);
  });
});
div {
  background-color: gold;
  border: 2px solid goldenrod;
  border-radius: 7px;
  text-align: center;
  vertical-align: middle;
  font-family: Arial;
  font-size: 35px;
  width: 100px;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <div><span id="test">0</span></div>
</body>
</html>

答案 1 :(得分:0)

试试这个 你需要增加淡出的回调,这意味着动画完成时增加

var count = 0;
$(document).ready(function() {
  $("div").on("click", function() {
    $("#test").fadeOut(500, function(){
      count++;
      document.getElementById("test").innerHTML = count;
      }
    );
  
    $("#test").fadeIn(500);
    
  });
});
div {
  background-color: gold;
  border: 2px solid goldenrod;
  border-radius: 7px;
  text-align: center;
  vertical-align: middle;
  font-family: Arial;
  font-size: 35px;
  width: 100px;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <div><span id="test">0</span></div>
</body>
</html>

答案 2 :(得分:0)

var count = 0;
$(document).ready(function() {
$("div").on("click", function() {
count++;
  $("#test").fadeOut(500).$("test").text(count).fadeIn(500);
});
});

&#34; JQuery Chaining&#34; https://www.w3schools.com/jquery/jquery_chaining.asp