一些潜水器的起始位置和随机移动
Start position and random movement for some divs
我想做一些类似于这个操作的事情,但让div从随机位置开始,而不是从左上角开始。
$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv();
newDiv();
});
function newDiv() {
var $div = $("<div class='a'>");
$(".animatedDivs").append($div);
animateDiv();
function animateDiv() {
var newq = makeNewPosition();
var oldq = $div.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$div.animate({
top: newq[0],
left: newq[1]
}, speed, 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 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 = .4;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="animatedDivs"></div>
我已经在这里为您更新了jsfiddle
只是简单地添加了这两行:
var newq = makeNewPosition();
var $div = $("<div class='a'>").css({top: newq[0], left: newq[1]});
$(document).ready(function () {
newDiv();
newDiv();
newDiv();
newDiv();
newDiv();
newDiv();
});
function newDiv() {
var newq = makeNewPosition();
var $div = $("<div class='a'>").css({top: newq[0], left: newq[1]});
$(".animatedDivs").append($div);
animateDiv();
function animateDiv() {
var newq = makeNewPosition();
var oldq = $div.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$div.animate({
top: newq[0],
left: newq[1]
}, speed, 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 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 = .4;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="animatedDivs"></div>
相关文章:
- 在固定位置显示随机图像
- 在两个位置显示数组中的随机单词
- 使用jQuery为位置创建随机css值
- JQuery-随机元素在容器内的绝对位置和旋转
- 根据页面上的位置设置随机类
- 为什么引导面板的位置在 Meteorjs 上是随机的
- 如何克隆图像并将其放置在随机位置
- 随机播放数组,因此没有两个键位于同一位置
- 开玩笑:测试数组的随机位置
- 谷歌地图API使用Math.random获取随机位置 - JS
- 返回包含随机位置元素的数组
- 在随机位置与空格匹配字符串
- 功能,在关闭浏览器时打开几个随机大小和位置的新窗口
- 如何使气泡图随机位置
- 启动HTML5<音频>在随机位置
- 使用JavaScript和html将图像和超链接从一个位置随机移动到另一个位置
- 使用jQuery将文本按字面顺序分解到随机位置
- 随机化容器内元素的位置
- 在HTML5蛇游戏中为食物生成随机位置时发生未捕获的TypeError
- 随机img位置添加&移除循环