我在我的网站上使用了一些小动画来增加数字,请参阅http://jsfiddle.net/zQ5AL/ 我想做的是拥有2-3种不同的动画(实际上是相同的动画,但numberValue和文本会有所不同),这样每次用户刷新页面时,他都会得到一个不同的数字(预先设置)和文本(即900是鸟的数量,1300只猫的数量,80只狗的数量等)。我该怎么做?
非常感谢,
<p id="dynamic-number">1</p>
<p class="dynamic-text">Number of birds</p>
JS:
var currentNumber = $('#dynamic-number').text();
$({numberValue: currentNumber}).animate({numberValue: 900}, {
duration: 2000,
easing: 'swing',
step: function() {
$('#dynamic-number').text(Math.ceil(this.numberValue));
}
});
答案 0 :(得分:2)
试试这个
function changeNumber(txtc,num){
$('#'+txtc).text('1');
var currentNumber = $('#dynamic-number').text();
var x = Math.floor((Math.random() * num) + 1);
$({numberValue: currentNumber}).animate({numberValue: x}, {
duration: 2000,
easing: 'swing',
step: function() {
$('#'+txtc).text(Math.ceil(this.numberValue));
}
});
}
changeNumber('dynamic-number1',900);
changeNumber('dynamic-number2',1300);
changeNumber('dynamic-number3',80);
<强> DEMO 强>
答案 1 :(得分:0)
试试:
HTML
<p id="dynamic-number" class="dynamic-number">1</p>
<p class="dynamic-text">Number of birds</p>
<p id="dynamic-number2" class="dynamic-number">1</p>
<p class="dynamic-text">Number of Rats</p>
CSS
.dynamic-number {
width: 100px;
height: 40px;
padding: 20px;
background: red;
font: bold 35px Arial;
color: #fff;
text-align: center;
}
.dynamic-text {
font: bold 35px Arial;
color: blue;
text-align: left;
}
的javascript
DoAnimation(700,'#dynamic-number');
DoAnimation(500,'#dynamic-number2');
function DoAnimation(nv,id) {
var currentNumber = $(id).text();
$({numberValue: currentNumber}).animate({numberValue: nv}, {
duration: 2000,
easing: 'swing',
step: function() {
$(id).text(Math.ceil(this.numberValue));
}
});
}
<强> DEMO 强>
答案 2 :(得分:0)
这是小提琴:http://jsfiddle.net/w346Q/2/
Math.random中的随机数()
来自消息数组的随机消息。
var currentNumber = $('#dynamic-number').text();
var randMsg = ["Number of birds", "Aeroplanes flying", "Aliens seen", "Greetings received", "Messages Sent", "Your Personal Message"];
var n = Math.floor(Math.random() * randMsg.length);
$('.dynamic-text').text(randMsg[n]);
var maxNo = 1000;
var randNo = Math.ceil(Math.random() * maxNo);
$({
numberValue: currentNumber
}).animate({
numberValue: randNo
}, {
duration: 2000,
easing: 'swing',
step: function () {
$('#dynamic-number').text(Math.ceil(this.numberValue));
}
});
您可以自定义它:
maxNo
randMsg
数组<强>更新强>
如果您的号码已预先定义:http://jsfiddle.net/w346Q/4/
var currentNumber = $('#dynamic-number').text();
var randMsg = ["Number of birds", "Aeroplanes flying", "Aliens seen", "Greetings received", "Messages Sent", "Your Personal Message"];
var randNo = [800,90,700,99,600,56];
var n = Math.floor(Math.random() * randMsg.length);
$('.dynamic-text').text(randMsg[n]);
$({
numberValue: currentNumber
}).animate({
numberValue: randNo[n]
}, {
duration: 2000,
easing: 'swing',
step: function () {
$('#dynamic-number').text(Math.ceil(this.numberValue));
}
});
在json数据的帮助下也可以实现同样的效果。