gpt4 book ai didi

javascript - JS动画从零到当前量

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:56 26 4
gpt4 key购买 nike

每次单击按钮时,它都会增加 +10(计数器)宽度。每次单击按钮时,我都希望动画从宽度 0 变为“计数器”宽度,但它总是从最后一个位置开始。我希望动画从 0px 到“counter”px请问你知道怎么解决吗?谢谢:)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
font-size: 50px;
}
#demo {
width: 100px;
height: 100px;
background-color: #f00;
transition: width 1s ease;
}

</style>
</head>
<body>
<div id="demo">
<br><br><br>
<button onclick="myFunction()">TRY</button>
</div>
</body>
<script type="text/javascript">
counter = 0;
function myFunction() {
document.getElementById("demo").style.width="0px";
counter+=10;
document.getElementById("demo").style.width=counter+"px";
}
</script>
</html>

最佳答案

使用 setTimeout() 并将 duration 设置为与 css transition 相同,调用 document。 getElementById("demo").style.width = counter + "px";setTimeout()

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
font-size: 50px;
}
#demo {
width: 100px;
height: 100px;
background-color: #f00;
transition: width 1s ease;
}
</style>
</head>

<body>
<div id="demo">
<br>
<br>
<br>
<button onclick="myFunction()">TRY</button>
</div>
</body>
<script type="text/javascript">
counter = 0;

function myFunction() {
document.getElementById("demo").style.width = "0px";
counter += 10;
setTimeout(function() {
document.getElementById("demo").style.width = counter + "px";
}, 1000)
}
</script>

</html>

关于javascript - JS动画从零到当前量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40428911/

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