小方块靠着浏览器运动

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{margin: 0;padding: 0;}
#div1{
width:100px;
height:100px;
background-color: #00FFFF;
position: absolute;
z-index: 3;
}
button{
margin: 100px auto;
margin-left: 500px;
font-size: 30px;
height: 100px;
width: 200px;
}
</style>
</head>
<body>
<div id="div1"></div>
<button type="button">点击停止</button>
</body>
<script type="text/javascript">
var div = document.getElementById('div1');
var btn = document.querySelector("button");
var timer;
var W = document.documentElement.clientWidth - div.offsetWidth ;
var H = document.documentElement.clientHeight - div.offsetHeight;
btn.onclick = ()=>{
clearInterval(timer)
}
step = 10;
div.onclick =()=>{
clearInterval(timer)
timer = setInterval(()=>{
if(div.offsetTop <=0 && div.offsetLeft >= 0){
div.style.left = div.offsetLeft + step + 'px';
if(parseInt(div.style.left) >= W){
div.style.left = W +'px'
}
}
if(parseInt(div.style.left) >= W && div.clientTop == 0 ){
div.style.top = div.offsetTop +step + "px";
if(parseInt(div.style.top) >= H){
div.style.top = H +'px'
div.style.left = W +'px'
}
console.log(div.offsetLeft ,W)
}
if(div.offsetTop == H && div.offsetLeft <= W ){
div.style.left = div.offsetLeft - step + 'px';
if(parseInt(div.style.left) <= 0){
div.style.left = 0 ;
}
}
if(div.offsetTop <= H && parseInt(div.style.left) <= 0){
div.style.top = div.offsetTop - step + "px";
if(parseInt(div.style.top) <= 0){
div.style.left = 0
}
}

},30)
}
</script>
</html>

posted @ 2019-07-24 20:40  陈小浩  阅读(92)  评论(0编辑  收藏  举报