我有这个简单的jquery逻辑,如何将其转换为纯JavaScript?
此外,我必须在React with Typescript中使用此代码。
我不知道该从哪里开始。任何帮助将不胜感激。
$('.counting').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 3000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
我已经将其转换为开始动画功能。
let counting = document.querySelectorAll(".counting");
let countingArray = Array.prototype.slice.call(counting);
countingArray.forEach((el) => {
let countTo = el.getAttribute("data-count");
//start animate...
为您提供动画功能:
function animate(render, from, to, duration, timeFx) {
let startTime = performance.now();
requestAnimationFrame(function step(time) {
let pTime = (time - startTime) / duration;
if (pTime > 1) pTime = 1;
render(from + (to - from) * timeFx(pTime));
if (pTime < 1) {
requestAnimationFrame(step);
}
});
}
render
是您希望用来更新新值的回调函数;from
并且to
是初始值和动画的目标值;duration
是动画在时间上的持续时间(以毫秒为单位);timeFx
是从[0,1]到[0,1]的计时功能。您可以将其用作:
countingArray.forEach((el) => {
let countTo = el.getAttribute("data-count");
animate(function(newValue) {
el.innerText = Math.floor(newValue);
}, 0, countTo, 3000, x => x);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句