html代码:
<div id="box"></div>
css代码:
<style>
* {
margin: 0;
padding: 0;
}
body {
position: relative;
}
#box {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: hotpink;
}
</style>
javascript代码:
<script>
window.onload = function() {
var box = document.getElementById('box');
// 设置运动速度
var step = 3;
setInterval(function() {
var left = box.offsetLeft + step;
if (left >= document.documentElement.clientWidth - box.offsetWidth) {
left = document.documentElement.clientWidth - box.offsetWidth;
step = -3;
} else if (left < 0) {
left = 0;
step = 3;
}
// 设置样式
box.style.left = left + 'px';
}, 16)
}
</script>