gpt4 book ai didi

javascript - 如何利用 while 循环来制作动画并显示总计

转载 作者:行者123 更新时间:2023-12-03 01:03:15 26 4
gpt4 key购买 nike

我正在尝试根据用户的输入对总量进行动画处理。用户输入一些数字后,总数会从 0 动画到总金额。在阅读了各种书籍后,我有点困惑,并认为 StackOverflow 将是练习 javaScript 的最佳方式。请告诉我我的代码哪里出了问题。

代码如下:

<body>
<div>
<label for="price">Price:</label>
<input type="text" id="price" name="price">
<br>
<label for="Quantity">Quantity:</label>
<input type="text" id="quantity" name="quantity">
<br>
<label for="Amount">Amount:</label>
<input type="text" id="amount" name="amount">
</div>
<script>
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var amount = price * quantity;
var length;

function updateAmount(){
while(amount = 0; amount <= amount.length; amount++){
document.getElementById("amount").value;
}

setInterval(updateAmount, 10);

正如你从我的代码中看到的,我有点困惑。如果您能引导我走向正确的方向,我将不胜感激。

最佳答案

我建议调查requestAnimationFrameeasing equations 。它们在处理动画时会有很大帮助。

我创建了一个示例 JSFiddle向您展示 requestAnimationFrame 和游戏中的缓动方程。

HTML

<div>
<label for="price">Price:</label>
<input type="number" id="price" name="price">
<label for="Quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity">
<label for="Amount">Amount:</label>
<div id="amount"></div>
</div>

JS

var priceInput = document.querySelector("#price");
var quantityInput = document.querySelector("#quantity");
var amountDiv = document.querySelector("#amount");

priceInput.addEventListener('keyup', update);
quantityInput.addEventListener('keyup', update);


var aid = null; // request animation id
var startTime = 0;
var duration = 1000; // in milliseconds
var amount = 0;
var begin = 0;
var change = 0;

function update() {
if (aid !== null) {
cancelAnimationFrame(aid);
}

var price = parseFloat(priceInput.value || 0);
var quantity = parseInt(quantityInput.value || 0);
startTime = performance.now();
begin = amount;
change = (price * quantity) - begin;
aid = requestAnimationFrame(step);
}

function step(ts) {
aid = requestAnimationFrame(step);
var elapsed = ts - startTime;
if (elapsed < duration) {
amount = easeOutQuad(elapsed, begin, change, duration);
amountDiv.innerHTML = amount.toFixed(2);
}
else {
cancelAnimationFrame(aid);
amountDiv.innerHTML = (begin + change).toFixed(2);
}
}

// t = time
// b = begin
// c = change
// d = duration
function easeOutQuad(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}

关于javascript - 如何利用 while 循环来制作动画并显示总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52527738/

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