<!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>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 100px;
}
</style>
</head>
<body>
<button id="btn">move</button>
<div class="box"></div>
<script>
// 单击按钮 让div变速运动到1000px停止
var btn = document.getElementById("btn");
var oDiv = document.querySelector("div");
var timer = null;
btn.onclick = function() {
startMove(oDiv,1000);
}
var num = 0;
// 封装运动函数
function startMove(obj,target) {
clearInterval(timer);
timer = setInterval(function() {
var speed = (target-obj.offsetLeft)/10; //此时速度不是匀速不变的而是发生变化的
num += speed;
if ( obj.offsetLeft === target ) {
clearInterval(timer);
} else {
obj.style["left"] = num + "px";
//obj.style.left = num+'px';
// console.log(obj.style.left)
}
},20);
}
</script>
</body>
</html>
该物体运动时速度由快变慢
网友评论