gpt4 book ai didi

jQuery 在 .animate 之后多次更改颜色和文本

转载 作者:搜寻专家 更新时间:2023-10-31 08:51:58 24 4
gpt4 key购买 nike

问题是当我点击按钮时,div应该移动三次,每次移动后改变背景和文本,但是当我这样做的时候div 只分配最后一个 .css 和 .html

$(document).ready(function () {
$("#button").click(function () {
$(".square").animate({top: '250px'});
$(".square").html("My friend");
$(".square").css({
backgroundColor: "#aa0000",
color: "white"
});
//SECOND MOVE
$(".square").animate({left: '250px'});
$(".square").css({
backgroundColor: "yellow",
color: "white"
});
$(".square").html("NO");
//THIRD MOVE
$(".square").animate({top: '-10px'});
$(".square").html("YESSSSSSSSSSSSSSS");
//FOURTH MOVE
$(".square").animate({left: '-10px'});
$(".square").css({
backgroundColor: "Black",
color: "white"
});
$(".square").html("NOO")
});
<!-- Here's the html:  -->

<div id="content" class="wrapper box">
<button id="button">Go</button>
<article>
<div class="square">Hello</div>
<div class="output"></div>
</article>
<input type="text" id="number"/>
<button onclick="calculate();">Check</button>
<button onclick="sortArray();">Input array</button></div>

最佳答案

您需要在每个动画结束后触发的动画完成事件中为每个步骤添加一个函数。

参见:jQuery .animate() complete function:

尝试这样的事情:

$(document).ready(function () {
$("#button").click(function () {

$(".square").animate({top: '250px'}, 'slow', function() {

$(".square").html("My friend");
$(".square").css({
backgroundColor: "#aa0000",
color: "white"
});

//SECOND MOVE
$(".square").animate({left: '250px'}, 'slow', function() {
$(".square").css({
backgroundColor: "yellow",
color: "white"
});

$(".square").html("NO");

//THIRD MOVE
$(".square").animate({top: '-10px'}, 'slow', function() {
$(".square").html("YESSSSSSSSSSSSSSS");

//FOURTH MOVE
$(".square").animate({left: '-10px'}, 'slow', function() {
$(".square").css({
backgroundColor: "Black",
color: "white"
});
$(".square").html("NOO")
});

});

});

});
});
});

function calculate() { console.log("calculate");}
function sortArray() { console.log("sortArray");}
.square {
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" class="wrapper box">

<button id="button">Go</button>

<article>
<div class="square">Hello</div>
<div class="output"></div>
</article>
<input type="text" id="number"/>
<button onclick="calculate();">Check</button>
<button onclick="sortArray();">Input array</button></div>

编辑:

要更改 duration(速度),只需将速度作为第二个参数添加到 animate() 函数中,这样动画持续时间为 3000 毫秒,或者值越小动画越快:

$(".square").animate({top: '250px'}, 3000, function() {

关于jQuery 在 .animate 之后多次更改颜色和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40627189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com