index代码:
<div id="myDiv"></div>
CSS代码:
<style>
#div {
height: 100px;
width: 200px;
background-color: wheat;
position: absolute;
}
</style>
js代码:
<script>
document.getElementById("div").onclick = function () {
moveAnimated(this,{"width":400,"height":200,"left":100,"opacity":0.5},function () {
console.log(123);
})
}
//封装获取浏览器最终样式
function getStyle(element, attr) {
//判断浏览器是否支持这个方法
return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr];
}
//封装变速动画函数
// element:节点对象
// json:属性和属性值
//fn:回调函数
function moveAnimated(element,json,fn) {
// 先清理定时器,防止定时器累加,速度越来越快
clearInterval(element.timeId);
//每次的点击操作都只产生一个定时器,定时器的id值存储到一个对象的属性中
element.timeId = setInterval(function () {
var flag=true;//默认全部属性都到达目标值了
//循环得到所有的属性和对应的目标值
for(var attr in json){
//判断当前要改变的属性类型
if(attr=="opacity"){
// 获取元素当前透明度
//当前透明度和目标透明度放大一百倍,方便计算
var current = getStyle(element,attr)*100;//数字类型
var target=json[attr]*100;
//设置每次改变的值
var step = (target - current) / 10;
// 正数则向上取整,负数则向下取整
step = step > 0 ? Math.ceil(step) : Math.floor(step);
// 每次移动后的值
current += step;
element.style[attr] = current/100;
}else if(attr=="zIndex"){
element.style[attr]=json[attr];
}else{
// 获取元素当前属性值
var current = parseInt(getStyle(element,attr));//数字类型
// 获取目标位置
var target=json[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){
flag=false;
}
}
if (flag) {
//到达目标位置则清理定时器
clearInterval(element.timeId);
//所有的执行完成后调用回调函数
if(fn){
fn();
}
}
//测试代码
console.log("目标:" + target + ",当前:" + current + ",移动步数:" + step);
}, 20)
}
</script>