<style>
* {
margin: 0;
padding: 0;
}
.ball {
width: 100px;
height: 100px;
background: red;
border-radius: 50%;
position: absolute;
top: 200px;
left: 10px;
}
.warl-l {
width: 5px;
height: 500px;
background: black;
position: absolute;
left: 5px;
}
.warl-r {
width: 5px;
height: 500px;
background: black;
position: absolute;
left: 700px;
}
</style>
</head>
<body>
<button>开始</button>
<div class="warl-l"></div>
<div class="ball"></div>
<div class="warl-r"></div>
<script>
var o = document.querySelector('.ball');
var oWall_r = document.querySelector('.warl-r');
var wallLeft = document.querySelector('.warl-l');
var w = o.offsetWidth;//球的宽度
var wL_r = oWall_r.offsetLeft;//右边的宽度
var maxLeft = wL_r - w;//往右最大位移距离
var minLeft = wallLeft.offsetWidth + wallLeft.offsetLeft;//最小左边距
var t;
document.querySelector('button').onclick = function () {
t = setInterval(move, 10);
};
//向右移动
function move() {
var l = o.offsetLeft;//取出小球的左边距
if (l >= maxLeft) {
clearInterval(t);
setInterval(moveLeft, 10);
} else {
o.style.left = l + 5 + 'px';
}
}
function moveLeft() {
var l = o.offsetLeft;//取出小球的左边距
if (l <= minLeft) {
clearInterval(t);
setInterval(move, 10);
} else {
o.style.left = l - 5 + 'px';
}
}
</script>
</body>
动画(一个小球在两个柱子间来回移动)
最新推荐文章于 2023-05-27 10:18:08 发布