我正在寻找创建一些可以在固定 div 容器内随机移动的东西。我喜欢在这个例子中物体移动的方式,我发现搜索这个网站......
http://jsfiddle.net/Xw29r/15/ http://jsfiddle.net/Xw29r/15/
jsfiddle上的代码包含以下内容:
$(document).ready(function(){
animateDiv();
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
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.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}
CSS:
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
但是,我不认为上面的代码根本限制了该对象。我需要我的对象在容器内随机移动,也就是说现在......宽度为 1200 像素,高度为 500 像素。
有人可以引导我走向正确的方向吗?我对编码非常陌生,所以我很难自己找到答案。
这是一个具有您正在寻找的功能的jsfiddle:http://jsfiddle.net/2TUFF/ http://jsfiddle.net/2TUFF/
JavaScript:
$(document).ready(function() {
animateDiv();
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window))
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $('.a');
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv();
});
};
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.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
HTML:
<div id="container">
<div class='a'></div>
</div>
CSS:
div#container {height:100px;width:100px;}
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
这将允许您创建具有任何高度/宽度的包装元素,并使浮动元素保持在其容器区域内。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)