function my$(){
return document.getElemtneById(id);
}
下面的my$的意思是为了简写代码
<style> * { margin: 0; padding: 0; } div { width: 200px; height: 100px; background-color: red; position: absolute; left: 0; top: 0; } input { z-index: 10; position: absolute; left: 0; top: 0; } </style> </head> <body> <input type="button" value="移动到400px" id="btn1"> <div id="dv"></div> <script src="common.js"></script> <script> //匀速动画封装函数 //element----元素 //attr----属性名字 //json键值对 function animate(element,json,fn) { clearInterval(element.timeId); element.timeId = setInterval(function () { var flag =true; for (var attr in json) { if(attr=="opacity"){//判断这个属性中是不是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"){//判断这个属性中是不是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==true) { clearInterval(element.timeId); //所有的属性到达目标才能使用这个函数,前提是用户传入了这个函数 if (fn){ fn(); } } //测试代码 console.log("目标位置:"+target+",当前位置:"+current+",每次移动的步数"+step+"") }, 20); } //获取计算后属性值函数----任意一个元素的一个属性值 function getStyle( elemtnt,attr) { return window.getComputedStyle?window.getComputedStyle(elemtnt,null)[attr]:elemtnt.currentStyle[attr]; } my$("btn1").onclick = function () { var json1 = {"width": 400, "height": 500, "left": 500, "top": 80, "opacity": 0.2}; animate(my$("dv"), json1, function () { animate(my$("dv"), {"width": 140, "height": 150, "left": 0, "top": 0, "opacity": 1, "zIndex": 1000}); }); }; /* my$("btn").οnclick=function () { console.log(getStyle(my$("dv"),"left")); }*/ </script>