两个盒子减速运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: aquamarine;
position: absolute;
top: 0px;
left: 0px;
}
.bs {
width:100px;
height:100px;
background-color: yellowgreen;
position: absolute;
top:400px;
left: 700px;
}
</style>
</head>
<body>
<div id="box"></div>
<div class="bs" id="bs"></div>
<script>
var box = document.getElementById("box");
var bs = document.getElementById("bs");
jiansu(box, "left",600);
jiansu(bs, "left",0);
function jiansu(obj, attr, target) {
function getStyle(obj, attr) {
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}
obj.onclick = function () {
var timer;
clearInterval(timer);
timer = setInterval(function () {
// 获取的left值带有px单位。
var boxLeft = parseInt(getStyle(obj, attr));
console.log(boxLeft)
// 取上限,最大值(目标值)才会是target:600px;
var step = Math.ceil((target - boxLeft) / 10);
var step = step > 0 ? Math.ceil((target - boxLeft) / 10) : Math.floor((target - boxLeft) / 10)
obj.style[attr] = boxLeft + step + "px";
}, 100)
}
}
</script>
</body>
</html>
完整版代码,粘贴可以直接使用。