我正在制作一个计数器,以便当页面滚动到某个位置时,计数器开始并以动画形式显示已在 HTML 中设置的数字。
我是编程方面的新手,想知道如何为计数器设置动画。另外,如何获得页面滚动的位置。
同样在我的代码中,我不知道我的逻辑是否正确,但我的 setInterval
根本不起作用。我该如何处理?
http://jsfiddle.net/a1t5m48f/2/
function Counter() {
this.element = document.getElementsByClassName('counter-number');
var intervalId;
var that = this;
this.init = function() {
for (var i = 0; i < that.element.length; i++) {
intervalId = setInterval(that.animate(i), 1000);
}
}
this.animate = function(i) {
var j = 0;
that.element[i].innerHTML = j;
j++;
if (j == parseInt(that.element[i].innerHTML)) {
clearInterval(intervalID);
}
console.log('hello');
}
}
var counter = new Counter();
counter.init();
最佳答案
使用一个setTimeout()
计时器比使用多个setInterval()
计时器更可取。在 .init()
方法计数器目标值存储在内部属性中,当前值设置为零。存储在 .indices
数组中的事件计数器索引。当在 .animate()
中达到目标值时,计数器元素索引将从该数组中删除。如果数组中有一些活跃的计数器,我们设置一个新的定时器来延迟后调用下一次迭代。动画在空 .indices
数组上停止。
var counter;
var pos = 200;
function Counter() {
this.element = document.getElementsByClassName('counter-number');
this.currentValues = [];
this.targetValues = [];
this.indices = [];
var that = this;
this.init = function() {
var value;
for (var i = 0; i < that.element.length; i++) {
that.indices.push(i);
that.targetValues.push(parseInt(that.element[i].innerHTML));
that.currentValues.push(0);
that.element[i].innerHTML = '0';
}
setTimeout(that.animate, 1000);
}
this.animate = function() {
var value;
var index;
var indicesToRemove = [];
for (var i = 0; i < that.indices.length; i++) {
index = that.indices[i];
if (that.currentValues[index] < that.targetValues[index]) {
that.currentValues[index]++
that.element[index].innerHTML = that.currentValues[index].toString();
} else {
indicesToRemove.push(i);
}
}
while (indicesToRemove.length > 0) {
i = indicesToRemove.pop();
that.indices.splice(i, 1);
}
if (that.indices.length > 0) {
setTimeout(that.animate, 1000);
}
}
}
window.onscroll = function() {
if ('undefined' === typeof counter
&& (document.body.scrollTop > pos || document.documentElement.scrollTop > pos)
) {
counter = new Counter();
counter.init();
}
}
关于javascript - 如何在页面到达某个位置时启动计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34248678/