如何构建开始按钮以加载计数器?

时间:2018-02-04 15:13:15

标签: javascript jquery html css

我创建了一个计数器,我希望它只在我按下按钮开始时启动(不在页面加载时)。我怎么能这样做?

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
      countNum: countTo
    },

    {

      duration: 6000,
      easing: 'linear',
      step: function() {
        $this.text(Math.floor(this.countNum));
      },
      complete: function() {
        $this.text(this.countNum);
        //alert('finished');
      }

    });



});
body {
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  font-size: 16px;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  display: inline;
}

.startbtn {
  margin-bottom: 40px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div class="startbtn">Start</div>

<div class="counter" data-count="378">0</div> km
<div class="counter" data-count="147">0</div> km
<div class="counter" data-count="60">0</div> minut

1 个答案:

答案 0 :(得分:0)

向您的元素click添加startbtn个事件。

请查看此代码段

点击开始。

var start = function() {
  $('.counter').each(function() {
    var $this = $(this), countTo = $this.attr('data-count');

    $({
      countNum: $this.text()
    }).animate({
        countNum: countTo
      }, {
        duration: 6000,
        easing: 'linear',
        step: function() {
          $this.text(Math.floor(this.countNum));
        },
        complete: function() {
          $this.text(this.countNum);
          //alert('finished');
        }
      });
  });
};

$('#startbtn').click(start);
body {
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  font-size: 16px;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  display: inline;
}

.startbtn {
  margin-bottom: 40px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div class="startbtn" id='startbtn'>Start</div>

<div class="counter" data-count="378">0</div> km
<div class="counter" data-count="147">0</div> km
<div class="counter" data-count="60">0</div> minut

请参阅?在您点击元素start之前,计数器才会执行。