<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
padding: 0;
margin: 0;
}
div {
width: 200px;
height: 100px;
background-color: pink;
position: absolute;
}
</style>
</head>
<body>
<input type="button" id="bt" value="显示效果"/>
<div id="dv"></div>
<script src="common.js"></script>
<script>
//点击按钮移动div
my$("bt").onclick = function () {
// animate(my$("dv"), "left", 400);
// animate(my$("dv"), "top", 100);
animate(my$("dv"), "width", 400);
};
//获取任意的一个属性的当前的属性值: left--->此时的left属性的值,width---当前的元素的宽
function getStyle(element, attr) {
//判断浏览器是否支持这个方法
return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr];
}
//匀速动画
//element---元素
//attr---属性名字
//target---目标位置
//缓动动画
function animate(element, attr, target) {
//清理定时器
clearInterval(element.timeId);
element.timeId = setInterval(function () {
//获取元素的当前位置
var current = parseInt(getStyle(element, attr));
//移动的步数
var step = (target - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
current += step;
element.style[attr] = current + "px";
if (current == target) {
//清理定时器
clearInterval(element.timeId);
}
//测试代码:
console.log("目标位置:" + target + ",当前位置:" + current + ",每次移动步数:" + step);
}, 20);
}
</script>
</body>
</html>