当页面到达某个位置时如何启动计数器?

时间:2015-12-13 06:47:20

标签: javascript html css counter setinterval

我正在制作一个计数器,当页面滚动到某个位置时,计数器会启动并动画显示已经在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();

2 个答案:

答案 0 :(得分:1)

使用一个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();
  }
}

答案 1 :(得分:0)

function whatsMyPosition(){
    scrollPosition = {
        y: window.pageYOffset
    }
    scrollPosition.y === something ? do Something;
}