<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
padding:0px;
margin:0px;
}
.box{
width: 200px;
height: 200px;
background: blue;
position: absolute;
left:0px
}
.box2{
background: red;
margin-top: 210px;
}
</style>
</head>
<body>
<!-- 盒子移动动画 -->
<div class="box box1"></div>
<div class="box box2"></div>
<script type="text/javascript">
var box1 = document.querySelector('.box1');
var box2 = document.querySelector('.box2');
//匀速运动 分装上面的代码块设计一个匀速运动的函数
function move(obj,target){
obj.myInter = setInterval(function(){
var offsetLeft = obj.offsetLeft;
// console.log(offsetLeft);
var num = 10;//每次都移动10个像素
// var target = 100;
if(offsetLeft==target){
//清除定时器
clearInterval(obj.myInter);
}else{
obj.style.left = offsetLeft+num+'px';
}
},1000)
}
box1.onclick = function(){
move(this,100);
}
// 缓动运动 有个滑动效果 每次移动的距离 由大到小改变
// 思路 要移动100 可以先走40 再走30 再走20 再走10 这样移动就会越来越慢
function slow(obj,target){
obj.myInter = setInterval(function(){
var offsetLeft = obj.offsetLeft;
var num = (target-offsetLeft)/10;
// Math.ceil向上取整 Math.floor向下取整
num>0?num = Math.ceil(num):num=Math.floor(num);
//注意 随着定时器的运行 num数值会由大到小发生变化
// 因为offsetLeft的值在变大
if(offsetLeft==target){
clearInterval(obj.myInter);//清除定时器
}else{
obj.style.left = offsetLeft+num+'px';
}
},1000)
}
box2.onclick = function(){
slow(this,100);
}
</script>
</body>
</html>