<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{padding: 0;margin: 0;}
#box{width: 100px;height: 100px;background-color: red;position: absolute;
border-radius: 50%;top: 100px;left: 52px;}
.wall{width: 2px ;height: 500px;background-color: black;position: absolute;}
.wl{left: 50px;}
.wr{left: 500px;}
</style>
</head>
<body>
<button id="btn">开始</button>
<div id="box"></div>
<div class ="wall wl"></div>
<div class ="wall wr"></div>
<script type="text/javascript">
/*
点击开始按钮,小球向右移动,碰到墙时,开始向左移动
碰到左墙时,向右移动----->小球在两堵墙之间移动
offset-
offsetLeft offsetTop offsetWidth offsetHeight......
此类属性是只读的
*/
var ball=document.querySelector('#box');
var t;
//向右移动
document.querySelector('#btn').onclick=function(){
moveHor();
};
//向右移动
function moveHor(speed){
//获取当前左边距
//var preLeft=window.getComputedStyle(ball,null).left;
var preLeft=ball.offsetLeft;
preLeft=parseInt(preLeft);//去除单位
ball.style.left=preLeft+speed+'px';
if (preLeft==52) {
clearInterval(t);//清除定时器
//启动定时器
t=setInterval(moveHor,10,6);
}
if (preLeft==400) {
clearInterval(t);//清除定时器
//启动定时器
t=setInterval(moveHor,10,-6);//按照指定的的周期(以毫秒计)来调用函数或计算表达式
}
}
</script>
</body>
</html>
javascript制作圆在两墙之间运动效果
最新推荐文章于 2025-05-31 15:07:03 发布