<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>匀速运动</title>
<style>
#div1 {
width: 50px;
height: 150px;
background: red;
position: absolute;
left: 500px;
}
span {
width: 1px;
height: 300px;
background: black;
position: absolute;
left: 300px;
}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById(‘div1‘);
var oBtn = document.getElementById(‘btn1‘);
oBtn.onclick = function() {
startMove(300);
}
}
var timer = null;
function startMove(iTarget) {
var oDiv = document.getElementById(‘div1‘);
clearInterval(timer);
timer = setInterval(function() {
var iSpeed = 0;
if (oDiv.offsetLeft < iTarget) {
iSpeed = 7;
} else {
iSpeed = -7;
}
if (Math.abs(oDiv.offsetLeft - iTarget) < 7) {
clearInterval(timer);
oDiv.style.left = iTarget + ‘px‘;
} else {
oDiv.style.left = oDiv.offsetLeft + iSpeed + ‘px‘;
}
}, 30);
}
</script>
</head>
<body>
<input id="btn1" type="button" name="" value="移动" style="margin:10px;">
<div id="div1"></div>
<span></span>
</body>
</html>
原文:http://www.cnblogs.com/Mr-W/p/6404865.html