js DOM弹球
html和css
## css
<style>
button {
margin: 0 100px;
}
#container {
width: 300px;
height: 300px;
margin: 50px auto;
background-color: #fff;
border: 1px solid #000;
position: relative;
}
.ball{
position: absolute;
width: 20px;
height:20px;
border-radius: 50%;
}
</style>
```
```html
## html
<button type="button" id="add">添加球</button>
<div id="container">
</div>
<script type="text/javascript">
let btn = document.getElementById('add');
let container =document.getElementById('container');
let colorArray =['red','blue','green','yellow','black'];
btn.addEventListener('click',function(){
let ball = document.createElement('div');
let i = Math.floor((Math.random()*40)%4);
ball.className = 'ball'
ball.style.backgroundColor = colorArray[i];
container.appendChild(ball);
let left = container.clientWidth/2-ball.offsetWidth/2,top= container.clientHeight/2-ball.offsetHeight/2;
let x=Math.floor(Math.random()*20),y=Math.floor(Math.random()*20);
setInterval(function(){
left=left+x;
top=top+y;
if(left<0||left>(container.offsetWidth-ball.offsetWidth)){
x=-x
}
if(top<0||top>(container.offsetHeight-ball.offsetHeight)){
y=-y
}
ball.style.left=left+'px';
ball.style.top=top+'px';
},30)
})
</script>
总结
**这个练习主要考察的是获取DOM的宽高
这里是别人整理链接:*https://www.cnblogs.com/itdansan/p/8116273.html***