![](/img/trans.png)
[英]I have a js script which should disable a button but it's not working
[英]JS Counter decrementing which should not have happened
以下是计数器的代码。 问题是它第一次运行正确,但每隔一次我按下按钮,计数就会减少。 比如第一次100,第二次45,第三次12等等!!!
我最后将变量的所有值设置为 0 但它仍然以相同的方式运行任何解决方案?
<div>
<button onclick="runAnimations()">Clients counter</button>
</h2>
<div class="panel">
<ul>
<li>
<span data-count="250" class="countup">250</span>+
</li>
<li>
<span data-count="500" class="countup">500</span>+
</li>
<li>
<span data-count="100" class="countup">100</span>+
</li>
</ul>
</div>
// How long you want the animation to take, in ms
const animationDuration = 2000;
// Calculate how long each ‘frame’ should last if we want to update the animation 60 times per second
const frameDuration = 1000 / 60;
// Use that to calculate how many frames we need to complete the animation
const totalFrames = Math.round( animationDuration / frameDuration );
// An ease-out function that slows the count as it progresses
const easeOutQuad = t => t * ( 2 - t );
// The animation function, which takes an Element
const animateCountUp = el => {
let frame = 0;
const countTo = parseInt( el.innerHTML, 10 );
// Start the animation running 60 times per second
const counter = setInterval( () => {
frame++;
// Calculate our progress as a value between 0 and 1
// Pass that value to our easing function to get our
// progress on a curve
const progress = easeOutQuad( frame / totalFrames );
// Use the progress value to calculate the current count
const currentCount = Math.round( countTo * progress );
// If the current count has changed, update the element
if ( parseInt( el.innerHTML, 10 ) !== currentCount ) {
el.innerHTML = currentCount;
}
// If we’ve reached our last frame, stop the animation
if ( frame === totalFrames ) {
clearInterval( counter );
}
}, frameDuration );
};
// Run the animation on all elements with a class of ‘countup’
const runAnimations = () => {
const countupEls = document.querySelectorAll( '.countup' );
countupEls.forEach( animateCountUp );
animationDuration = 0;
frameDuration = 0;
totalFrames = 0;
easeOutQuad = 0;
animateCountUp = 0;
countTo = 0;
progress = 0;
runAnimations = 0;
currentCount = 0;
frame = 0;
countupEls = 0;
};
首先,将这些值设置为0
不是一个好主意,尤其是因为它们中的大多数都是const
,所以它甚至是不可能的。 我认为代码的问题在于,以某种方式在相同元素上调用runAnimations
function 为时过早,因为您选择元素的当前文本作为计数器的结束编号,如果 animation 当前正在为该元素运行它只会为第二次运行选择一个较低的数字,因为那是那一刻的innerHTML
。 为了确保不会发生这种情况,将数字存储为像<div data-count="100" class="countup"></div>
这样的数据属性是一种更好的方法,因为它不会像innerHTML
那样改变的元素,你可以确保你的代码每次运行都使用正确的值。
按照你上面说的做,问题就解决了。
<div data-count="100" class="countup"></div>
const countTo = parseInt( el.getAttribute('data-count'), 10 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.