我创建了一个计数器,我希望它只在我按下按钮开始时启动(不在页面加载时)。我怎么能这样做?
$('.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
答案 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
之前,计数器才会执行。