做为《JS的DOM操作详解》中的一个进阶练习,制作一个可以在浏览器内自由反弹的方框。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="js/test.js" type="text/javascript" charset="utf-8"></script>
<title></title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
background-color: beige;
height: 100px;
width: 100px;
top: 0px;
left: 0px;
position: relative;
}
p {
text-align: center;
line-height: 100px;
}
</style>
<body>
<div id="box">
<p>Move me!</p>
</div>
<button type="button" onclick="changeDiv()">Boom!</button>
<button type="button" onclick="stopChangeDiv()">Stop!</button>
<script type="text/javascript">
var box=document.getElementById('box');
var timer;
function changeDiv(){
var x=10;
var y=10;
timer = window.setInterval(()=>{
var left=parseInt(window.getComputedStyle(box,null)['left']);
var top=parseInt(window.getComputedStyle(box,null)['top']);
var height=parseInt(window.getComputedStyle(box,null)['height']);
var width=parseInt(window.getComputedStyle(box,null)['width']);
var w=document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
var h=document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
if(left+width>w-10){
x=-10;
}else if(left<0){
x=10;
};
if(top+height>h-10){
y=-10;
}else if(top<0){
y=10;
};
box.style.left=left+x+'px';
box.style.top=top+y+'px';
console.log(left,x,top,y);
},100)
}
function stopChangeDiv(){
window.clearInterval(timer);
}
</script>
</body>
</html>
需要注意的知识点:
parseInt会获取第一个数字到第一个非数字之间的内容,所以可以顺利去掉单位- 判断向下和向右临界点的时候加了10px的偏移,避免出现滚动条
我是T型人小付,一位坚持终身学习的互联网从业者。喜欢我的博客欢迎在csdn上关注我,如果有问题欢迎在底下的评论区交流,谢谢。
本文介绍如何使用JavaScript在浏览器中创建一个可以自由反弹的方框,通过修改方框的位置属性并监听边界来实现反弹效果,展示了DOM操作和事件处理的实践。

被折叠的 条评论
为什么被折叠?



