1 <script> 2 window.onload = function() { 3 //var oDiv1 = document.getElementById('box1'); 4 //var oDiv2 = document.getElementById('box2'); 5 // oDiv1.timer = null; 6 var oDiv = document.getElementsByTagName('div'); 7 8 for (var i = 0; i < oDiv.length; i++) { 9 oDiv[i].timer = null; 10 oDiv[i].onmouseover = function() { 11 var that = this; //闭包的关系,把this传递过去 12 startMove(this, {'width': 205, 'height': 500},function(){ 13 startMove(that, {'opacity': 100}); 14 }); 15 //alert(getStyle(this,'opacity')) 16 } 17 oDiv[i].onmouseout = function() { 18 var that = this; 19 startMove(this, {'width': 200,'height':200}, function(){ 20 startMove(that, {'opacity': 30}); 21 }); 22 } 23 } 24 } 25 //var timer = null; 26 function getStyle(obj,name){ //获取样式的函数 27 if(obj.currentStyle){ 28 return obj.currentStyle[name]; //这里用这种形式的原因是name是以字符串的形式传递过来的 29 } else{ 30 return getComputedStyle(obj,false)[name]; //得到加上边框的总宽 31 } 32 } 33 //startMove(onj,{ 200, height: 200}, fnEnd) 34 function startMove(obj, json, fnEnd) { 35 clearInterval(obj.timer); 36 obj.timer = setInterval(function() { 37 var bStop = true; //开了定时器之后设立一个假设:所有运动都停止了,那些把假设设到定时器外面的都是错误的方法 38 for(var attr in json){ 39 var cur = 0; 40 if(attr == "opacity"){ 41 cur = Math.round(parseFloat(getStyle(obj,attr)) * 100); //要取整 42 } else { 43 cur = parseInt(getStyle(obj,attr)) 44 } 45 var speed = (json[attr] - cur) / 10; // 46 speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); 47 if (cur !== json[attr]) { //如果某次循环的值不等于目标值, 48 bStop = false; //假设不成立 49 }; 50 if (attr == "opacity"){ 51 obj.style.opacity = (speed + cur)/100; 52 obj.style.filter = 'alpha(opacity:'+ (speed + cur) +')'; 53 } else{ 54 obj.style[attr] = cur + speed + 'px'; 55 } 56 } 57 if(bStop){ //所有的假设都成立了,才关闭定时器 58 clearInterval(obj.timer); 59 if(fnEnd) fnEnd(); //如果有回调函数,则执行回掉函数 60 } 61 }, 30) 62 } 63 </script>
html代码
1 <div id="box1"></div> 2 <div id="box2"></div>
css代码
1 div { 2 200px; 3 height: 200px; 4 background: purple; 5 border: 10px solid maroon; 6 margin-top: 10px; 7 opacity: 0.3; 8 filter: alpha(opacity: 30); 9 }
全手打,亲测可用,支持多物体,多属性,链式,同时运动。