实现任意个球在窗口中四处乱碰的效果。
点击按钮,每次可以添加一个小球
核心代码如下:
<body>
<div id="one_box"></div>
<br>
<button>点击添加小球</button>
<script>
var divs=document.querySelectorAll("div");
var one_box=document.getElementById("one_box");
//获得视口的宽度
var viewClient = document.documentElement || document.body;
var viewWidth = viewClient.clientWidth;
var viewHeight = viewClient.clientHeight;
var button=document.querySelector("button");
//x轴的初始速度
button.onclick=function () {
var div=document.createElement("div");
var color=random(0,0xffffff+1);
// console.log(color);
color=color.toString(16);
//console.log(color);
div.style.backgroundColor='#'+color;
document.body.insertBefore(div,one_box);
var divs=document.querySelectorAll("div");
for (var i=0;i<divs.length;i++){
run(divs[i]);
}
};
const INTERVAL = 5;
function run(obj) {
var speedX=0;
var speedY=0;
//获得内部或者外部样式
var styles = getStyles (obj);
obj.timer=setInterval(function () {
var left = parseInt (styles.left);
if (left <= 0) {//左边界
speedX =random(0,4);
// console.log(speedX);
}
if(left >=viewWidth - obj.offsetWidth){//右边界
speedX = - (random(0,4));
}
//修改div的left样式
obj.style.left =left + speedX+"px";
var top = parseInt (styles.top);
if (top <= 0) {
speedY =random(0,4);
}
if(top >= viewHeight - obj.offsetHeight){//右边界
speedY = -(random(0,4));
}
//修改div的left样式
obj.style.top = top + speedY + "px";
},INTERVAL);
}
</script>
</body>
</html>