效果一:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
</head>
<body>
<button id="btn">走你</button>
<button id="btn2">回来</button>
<script type="text/javascript">
var div = document.createElement('div');
document.body.appendChild(div);
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "50px";
//走你按钮触发事件
document.getElementById('btn').onclick = function(){
var timeId = setInterval(function(){
div.style.left = parseInt(div.style.left) + 5 + "px";
if (div.style.left=='400px') {
clearInterval(timeId);
}
},50);
}
//回来按钮触发事件
document.getElementById('btn2').onclick = function(){
var timeId = setInterval(function(){
div.style.left = parseInt(div.style.left) - 5 + "px";
if (div.style.left=='0px') {
clearInterval(timeId);
}
},50);
}
</script>
</body>
</html>
两个div 封装:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document</title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 200px;
background: slateblue;
position: relative;
}
.box2 {
width: 200px;
height: 200px;
background: pink;
position: relative;
}
</style>
<body>
<button>走你</button>
<button id="back">后退</button>
<div class="box"></div>
<div class="box2"></div>
</body>
<script type="text/javascript">
var btn = document.getElementsByTagName('button')[0];
var box = document.getElementsByClassName('box')[0];
var box2 = document.getElementsByClassName('box2')[0];
var btn2 = document.getElementById('back');
var timer;
btn.onclick = function(){
/*动画的公式
leader = leader + step
元素的自身位置 = 元素位置 + 每次移动的速度
*/
animate(box,300);
animate(box2,600);
}
btn2.onclick = function(){
//alert('111');
animate(box,0);
animate(box2,0);
}
// 封装
function animate(obj,distance){
obj.timer = setInterval(function(){
var leader = obj.offsetLeft;
console.log(leader);
var step = 10;
console.log(step);
step = leader>distance?-step:step;
leader == distance?clearInterval(obj.timer):obj.style.left = leader + step + "px";
},16);
}
</script>
</html>