[英]Creating a fancy calculation for price in Javascript?
I've got 2 prices:我有2个价格:
Price1: $5000价格 1:5000 美元
Price2: $2000价格 2:2000 美元
What I want is JavaScript to calculate the total live on the page, so when the div loads, that it starts calculating.我想要的是 JavaScript 来计算页面上的总活动时间,所以当 div 加载时,它开始计算。
But I don't just want to instantly see $7000 right there.但我不只是想立即看到 7000 美元。 I want it to 'animate' the result.我希望它为结果“制作动画”。 So go from $0 to $1, $2, $3, $4, $5 ... $5000, $5001, $5002 ... $7000.所以从 0 美元到 1 美元、2 美元、3 美元、4 美元、5 美元……5000 美元、5001 美元、5002 美元……7000 美元。
I also want the price that it's currently adding below the line that's adding to.我还希望它当前添加的价格低于添加到的线。
EX:前任:
Total: $TOTALPRICE总计:$TOTALPRICE
Currently adding: Price1目前正在添加:Price1
Is this possible?这可能吗? If so how?如果是这样怎么办?
jQuery lets you .animate()
Docs any arbitrary value. jQuery 允许您.animate()
Docs任何任意值。
Access the current animated now
value using the step
method callback使用step
方法回调访问当前的动画now
值
var tot = 0, $p1 = $("#p1"), $p2 = $("#p2"), $tot = $("#tot"); function animateTotal() { tot = parseFloat($p1.val()) + parseFloat($p2.val()); $({ p: 0 }).animate({ p: tot }, { duration: 2000, easing: "swing", // "swing" is default, you can try another easing like "linear" step: function (now) { $tot.val( now.toFixed(2) ); } }); } $p1.add($p2).on("input", animateTotal); $p1.trigger("input");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> $<input value="3000.50" id="p1" name="p1">PRICE1 +<br> $<input value="4000" id="p2" name="p1">PRICE2 =<br> $<input value="0" readonly id="tot" name="tot">
Update the UI as you add添加时更新 UI
Maybe try something like:也许尝试这样的事情:
(JQuery) (JQuery)
var existing = 0;
var numbersToAdd = [ 1, 30, 40];
$.each(numbersToAdd, function(i, e) {
fancyAdd(e, existing);
});
function fancyAdd(n, existing) {
$('#idOfResultDiv').innerHTML = n + existing;
existing = n + existing;
}
HTML HTML
<div id="idOfResultDiv"></div>
You can also use setTimeout
to delay execution您还可以使用setTimeout
来延迟执行
Fiddle working here : https://jsfiddle.net/v7n7fscv/小提琴在这里工作: https : //jsfiddle.net/v7n7fscv/
Try this code You will need a self invoking function because setTimeout() function is non blocking & will not block the for loop to be executed :试试这段代码您将需要一个自调用函数,因为 setTimeout() 函数是非阻塞的,并且不会阻塞要执行的 for 循环:
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js
"></script>
</head>
<body>
<div id="result">
</div>
</body>
<script type="text/javascript">
var a = 20;
var b = 20;
c = a+b;
var counter = 0;
(function next() {
if (counter++ >= c) return;
setTimeout(function() {
$("#result").html(counter);
next();
}, 0.00001);
})();
</script>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.