<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{margin: 0px;}
.div1{
border-radius: 60px;
width:100px;
height: 100px;
position: absolute;
background: burlywood;
top:10px;
line-height: 100px;
text-align: center;
font-size: 50px;
}
#warp{
width: 700px;
height: 700px;
background: chocolate;
}
</style>
</head>
<body>
<div id="warp">
<div class="div1">1</div>
<div class="div1">2</div>
<div class="div1">3</div>
<div class="div1">4</div>
<div class="div1">5</div>
<div class="div1">6</div>
<div class="div1">7</div>
<div class="div1">8</div>
<div class="div1">9</div>
<div class="div1">10</div>
<div class="div1">11</div>
<div class="div1">12</div>
</div>
</body>
</html>
<script>window.onload = function() {
var div1 = document.getElementsByClassName("div1")
//获取随机方向
start_position = function() {
var arr = [];
var x = Math.floor(Math.random() * 600);
var y = Math.floor(Math.random() * 600);
arr[0] = x;
arr[1] = y;
return arr;
}
//获取随机方向
start_direction = function() {
var arr = [];
var x = Math.floor(Math.random() * 600);
var y = Math.floor(Math.random() * 600);
var i, m;
if (x > 300) {
i = 1;
} else if (x <= 300) {
i = -1
}
if (y > 300) {
m = 1;
} else if (y <= 300) {
m = -1
}
arr[0] = i;
arr[1] = m;
return arr;
}
var run = function(obj, iX, iY, directX, directY) {
var iX = start_position()[0]
var iY = start_position()[1]
var directX = start_direction()[0];
var directY = start_direction()[1];
setInterval(function() {
iX = iX + directX;
iY = iY + directY;
obj.style.top = iY + "px";
obj.style.left = iX + "px";
if ((iX > 0 && iX < 600) && (iY < 0)) {
directY = 1
}
if ((iX > 0 && iX < 600) && (iY > 600)) {
directY = -1
}
if ((iY > 0 && iY < 600) && (iX > 600)) {
directX = -1
}
if ((iY > 0 && iY < 600) && (iX < 0)) {
directX = 1
}
var oneX = div1[0].offsetLeft + 50;
var oneY = div1[0].offsetTop + 50;
var twoX = div1[1].offsetLeft + 50;
var twoY = div1[1].offsetTop + 50;
var S = Math.floor(Math.sqrt(Math.pow((oneX - twoX), 2) + Math.pow((oneY - twoY), 2)));
}, 10)
}
run(div1[0]);
run(div1[1]);
run(div1[2]);
run(div1[3]);
run(div1[4]);
run(div1[5]);
// run(div1[6]);
// run(div1[7]);
// run(div1[8]);
// run(div1[9]);
// run(div1[10]);
// run(div1[11]);
}</script>
本文分享自 交互设计前端开发与后端程序设计 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!