前几天,一直想不明白,为什么需要封装,担当自己明白的什么才发现自己真的还是蠢到可以!不多说,看代码。
1.首先,简单的元素移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
input {
margin-top: 30px;
}
div {
margin-top: 30px;
width: 200px;
height: 100px;
background-color: greenyellow;
position: absolute;
transition: all 1s;
}
.zero{
left: 0;
transition: all 1s;
}
.fourHundred {
left: 400px;
transition: all 1s;
}
.eightHundred {
left: 800px;
transition: all 1s;
}
</style>
</head>
<body>
<button id="btn0">移动到400</button>
<button id="btn1">移动到800</button>
<button id="btn2">还原到000</button>
<div id="divBox" class="zero"></div>
<script>
//设置获取任意id
function my$(id) {
return document.getElementById(id);
}
//div移动之前需要脱离文档流---> position: absolute;
//点击移动400px
my$("btn0").onclick = function () {
my$("divBox").className = "fourHundred";
};
//点击移动800px
my$("btn1").onclick = function () {
my$("divBox").className = "eightHundred";
};
my$("btn2").onclick = function () {
my$("divBox").className ="zero";
}
</script>
</body>
</html>
2.封装后的元素移动,后台才突然发现其实是Jquery里的animate方法,蠢^~^
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$@任性的我@$</title>
<style>
* {
margin: 0;
padding: 0;
}
input {
margin-top: 30px;
}
div {
margin-top: 30px;
width: 200px;
height: 100px;
background-color: greenyellow;
position: absolute;
left: 50px;
}
</style>
</head>
<body>
<button id="btn0">移动到400</button>
<button id="btn1">移动到800</button>
<button id="btn2">还原到000</button>
<div id="divBox"></div>
<script src="common.js"></script>
<script>
//动画函数封装------任意一个元素移动到指定的目标位置
function animate(element, target) {
//先清理定时器
clearInterval(element.timeId);
//一会要清理定时器(只产生一个定时器)
element.timeId = setInterval(function () {
//获取div的当前的位置
var current = element.offsetLeft;//数字类型,没有px
//div每次移动多少像素---步数
var step = 10;
step = current < target ? step : -step;
//每次移动后的距离
current += step;
//判断当前移动后的位置是否到达目标位置
if (Math.abs(target - current) > Math.abs(step)) {
element.style.left = current + "px";
} else {
//清理定时器
clearInterval(element.timeId);
element.style.left = target + "px";//直接到达目标
};
}, 20);
};
//div移动之前需要脱离文档流---> position: absolute
//点击移动400px
my$("btn0").onclick = function () {
animate(my$("divBox"),400);
};
//点击移动800px
my$("btn1").onclick = function () {
animate(my$("divBox"),800);
};
my$("btn2").onclick = function () {
animate(my$("divBox"),50);
};
</script>
</body>
</html>