代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 150px;
height: 150px;
background: sandybrown;
position: absolute;
border: 2px solid #ccc;
left: 800px;
top: 28px;
}
</style>
</head>
<body>
<button>右走</button> <button>左走</button>
<div id="box"></div>
<script>
var box = document.getElementById('box');
var btn = document.getElementsByTagName('button');
var timer = null;
// 向右走
btn[0].onclick = function () {
run(box,'left',800,10)
}
// 向左走
btn[1].onclick = function () {
run(box,'left',0,10)
}
// box.onclick = function (){
// clearInterval(timer);
// timer = setInterval(function(){
// var cur = parseInt(getStyle(box,'left')); // 当前值
// // (目标值 - 当前值)/ 缩放比例
// var speed = Math.floor((0 - cur)/10); // 50 45 40.5
// if(cur == 0){
// clearInterval(timer);
// }
// box.style.left = cur + speed + 'px'; // 50 95 135.5
// },50)
// }
function run(ele,attr,target,param) {
clearInterval(timer);
timer = setInterval(function () {
var cur = parseInt(getStyle(ele, attr)); // 当前值
// (目标值 - 当前值)/ 缩放比例
var speed = (target - cur) / param; // 变速
speed = speed > 0? Math.ceil(speed) : Math.floor(speed); // 向右走 变速正数,需要向上取整,反之向左走 变速负数,需要向下取整
if (cur >= target&& speed>0 || cur<=target && speed<0) {
cur = target;
clearInterval(timer);
}
ele.style[attr] = cur + speed + 'px';
}, 50)
}
// 获取元素非行间样式
function getStyle(ele, attr) {
if (window.getComputedStyle) { // 标准
return getComputedStyle(ele)[attr];
} else { // ie
return ele.currentStyle[att];
}
}
</script>
</body>
</html>
效果