每当我单击按钮时,它就会增加+10(计数器)宽度。
我希望每次单击按钮时动画从宽度0变为“计数器”宽度,但始终从最后一个位置开始。
我希望动画从0px变为“反” 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/