JS小练习 小球运动
先上效果图
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
margin: 0 auto;
text-align: center;
}
.wall{
width: 500px;
height: 500px;
border: 5px solid lightgrey;
position: relative;
}
button{
width: 200px;
line-height: 50px;
color: white;
font-size: 20px;
font-weight: bolder;
background-color: skyblue;
border: none;
outline: none;
margin-top: 10px;
}
.boll{
width: 80px;
height: 80px;
border-radius: 50%;
background-color: cyan;
position: absolute;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="wall">
<div class="boll"></div>
</div>
<button>开始</button>
</div>
<script>
// 获取容器
var _wall = document.querySelector('.wall');
// 获取开始按钮
var _button = document.querySelector('button');
// 获取小球
var _boll = document.querySelector('.boll');
_button.onclick = function(){
// XY轴运动速度
var X = 5;
var Y = 8;
var id = setInterval(function(){
_boll.style.left = _boll.offsetLeft+X+'px';
_boll.style.top = _boll.offsetTop-Y+'px';
// 到最右边,反转运动方向
if(_wall.clientWidth-_boll.offsetLeft<=_boll.offsetWidth){
X*=-1;
}
// 到最上边,反转运动方向
if(_boll.offsetTop<=0){
Y*=-1;
}
// 到最左边,反转运动方向
if(_boll.offsetLeft<=0){
X*=-1;
}
// 到最下边,反转运动方向
if(_wall.clientHeight-_boll.offsetTop<=_boll.offsetHeight){
Y*=-1;
}
},10)
}
</script>
</body>
</html>
总结用到的知识
元素的可视距离: tag.clientHeight,tag.clientWidth
元素控件距离: tag.offsetHeight,tag.offsetWidth
被撑开的距离: tag.scrollHieght,tag.scrollWidth
元素的位置: tag.offsetLeft,tag.offsetTop
今天就到这,下课!♥