<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background-color: brown;
position: absolute;
left: 0;
top: 100px;
}
#line {
position: absolute;
width: 1px;
height: 100%;
left: 800px;
top: 0;
background-color: #000;
}
#box2 {
width: 100px;
height: 100px;
background-color: #40739e;
position: absolute;
right: 300px;
top: 0px;
}
#line2 {
position: absolute;
width: 100%;
height: 1px;
left: 0px;
top: 600px;
background-color: #40739e;
}
</style>
</head>
<body>
<button id="btn">移动到800px</button>
<div id="box"></div>
<div id="box2"></div>
<!-- 运动的终点线 -->
<div id="line"></div>
<div id="line2"></div>
<script>
/* 获取按钮 */
var btn = document.getElementById('btn')
/* 添加点击事件 */
btn.onclick = function() {
/* 获取盒子1 */
var box = document.getElementById('box')
/* 调用函数 */
fn(box, 800, 12, 'left')
/* 获取盒子2 */
var box2 = document.getElementById('box2')
/* 调用函数 */
fn(box2, 600, 7, 'top')
}
/* 封装为函数 */
function fn(el, target, step, attr) {
/* 判断是否为空 */
if (!el.timer) {
/* 获取元素的样式 */
var res = getComputedStyle(el)[attr]
/* 字符串转数字 */
res = parseInt(res)
/* 判断移动的方向 */
if (res - target > 0) {
//求绝对值取反。
step = -Math.abs(step);
}
/* 添加定时器 */
el.timer = setInterval(function() {
/* 获取元素的样式 */
var res = getComputedStyle(el)[attr]
/* 字符串转数字 */
res = parseInt(res)
/* 得出位置 */
var ad = res + step
/* 如果step大于0且ad等于target或...清除定时器 */
if ((step > 0 && ad >= target) || (step < 0 && ad <= target)) {
//结束运动 : 清除定时器,将物体直接运动到终点
clearInterval(el.timer);
el.style[attr] = target + 'px'
} else {
/* 否则继续执行 */
el.style[attr] = ad + 'px'
}
}, 20)
}
}
</script>
</body>