您可以使用它Math.random
来生成速度,但您首先必须弄清楚最大和最小速度 - 最小速度非常重要,因为 Math.random 可能会生成一个非常小的数字,以至于动画需要任意长的时间去完成。
[编辑]:OP询问是否可以只触发一次动画 - 我已经添加了该.unbind()
方法,并为该函数分配了一个处理程序。
<script>
// Assign handler name, so that we can unbind it specifically
$("#race").click(function animateSprite(){
// Unbind after first click
$(this).unbind('click', animateSprite);
// Set minimum speed
var minSpeed = 1000;
// Get random speed
var kimoSpeed = parseInt(minSpeed + Math.random()*1000, 10),
kahunaSpeed = parseInt(minSpeed + Math.random()*1000, 10);
// In this case, the lowest possible speed is 1000,
// and the highest possible speed is 2000.
// You are of course free to adjust the speed.
// Animate
$(".kimo").animate({"left": "+=550px"}, kimoSpeed);
$(".kahuna").animate({"left": "+=550px"}, kahunaSpeed);
// And if you want to decide who is the fastest, and assuming that you have an element with the id of "announce"
// Delay announcement by 500ms after the slowest racer
setTimeout(function(){
if(kimoSpeed < kahunaSpeed) {
// Declare Kimo as winner, e.g.
// $("#announce").text("Kimo has won the race!");
} else {
// Declare Kahuna as winner
// $("#announce").text("Kahuna has won the race!");
}
}, Math.max.apply(Math, [kimoSpeed, kahunaSpeed])+500);
});
</script>