如果有人对 jQuery 插件感兴趣(分叉相同的功能)更容易应用于页面中的多个元素。
HTML:
<div id="container">
<div class='a rand'></div>
<div class='b rand'></div>
<div class='c rand'></div>
</div>
CSS:
div#container {height:500px;width:500px;}
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
top:100px;
left:100px;
}
div.b {
width: 50px;
height:50px;
background-color:blue;
position:fixed;
top:10px;
left:10px;
}
div.c {
width: 50px;
height:50px;
background-color:green;
position:fixed;
top:200px;
left:100px;
}
jQuery插件:
(function($) {
$.fn.randomizeBlocks = function() {
return this.each(function() {
animateDiv($(this));
});
};
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
var h = $container.height() - 10;
var w = $container.width() - 10;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$target.animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv($target);
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.03;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
}( jQuery ));
用法:
$(document).ready(function() {
$('.rand').randomizeBlocks();
});
http://jsfiddle.net/fmvtb88d/