所以我找到了这个jquery函数:http://codepen.io/niklas-r/pen/HsjEv
html:
<p id="el">0%</p>
<button id="startCount">Count</button>
JS:
$("#startCount").on("click", function (evt) {
var $el = $("#el"),
value = 56.4;
evt.preventDefault();
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
});
它用动画增加数字。当我用document.ready()替换click时,它不起作用。我如何使它工作?
答案 0 :(得分:3)
document.ready
上的没有event
,因此您无法evt.preventDefault()
。
以下是文档就绪的实例:
$(function() {
var $el = $("#el"),value = 56.4;
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<p id="el">0%</p>
&#13;
答案 1 :(得分:0)
尝试使用这样的,
$(document).ready(function(){
$(document).on("click", "#startCount", function (evt) {
var $el = $("#el"),
value = 56.4;
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
});
});
答案 2 :(得分:0)
在$(document).ready中包含所有代码,以防止在页面加载之前执行脚本
$(document).ready(function(){
$("#startCount").on("click", function (evt) {
...
});
});
答案 3 :(得分:0)
要在就绪和按钮上激活,请单击:
var cnt = function() {
var $el = $("#el"),value = 56.4;
$({percentage: 0}).stop(true).animate({percentage: value}, {
duration : 2000,
easing: "easeOutExpo",
step: function () {
// percentage with 1 decimal;
var percentageVal = Math.round(this.percentage * 10) / 10;
$el.text(percentageVal + '%');
}
}).promise().done(function () {
// hard set the value after animation is done to be
// sure the value is correct
$el.text(value + "%");
});
};
$(cnt);
$("#startCount").on("click", cnt);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<p id="el">0%</p>
<button id="startCount">Count</button>
&#13;