<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ 200px; height: 100px; margin: 20px; float: left; background: red; border: blue 1px solid; } #div3{ 200px; height: 100px; margin: 20px; float: left; background: red; filter: alpha(opacity:30); opacity: 0.3; } </style> <script> window.onload = function () { var oDiv = document.getElementById('div1'); var oDiv2 = document.getElementById('div2'); var oDiv3 = document.getElementById('div3') oDiv.onmouseover = function(){ startMove(this,"height",300); }; oDiv.onmouseout = function(){ startMove(this,"height",100); }; oDiv2.onmouseover = function(){ startMove(this,"width",400); }; oDiv2.onmouseout = function(){ startMove(this,"width",200); } oDiv3.onmouseover = function(){ startMove(this,"opacity",100); }; oDiv3.onmouseout = function(){ startMove(this,"opacity",30); } } function getStyle(obj,name){ if (obj.currentStyle) { return obj.currentStyle[name]; } else { return getComputedStyle(obj,false)[name] } } //var alpha = 30;所有的东西都不能公用 function startMove (obj,attr,iTarget) { clearInterval(obj.time); obj.time = setInterval(function(){ var cur = 0; if (attr == 'opacity') {
cur = Math.round(parseFloat(getStyle(obj,attr))*100);
} else { cur = parseInt(getStyle(obj,attr)); } var speed = (iTarget-cur)/6; speed = speed>0?Math.ceil(speed):Math.floor(speed); if (cur == iTarget) { clearInterval(obj.time); } else { if (attr == 'opacity') { obj.style.filter = 'alpha(opacity:'+(cur+speed)+')'; obj.style.opacity = (cur+speed)/100; } else { obj.style[attr] = cur+speed+'px'; } } },30) } </script> </head> <body> <div id="div1">变高</div> <div id="div2">变宽</div> <div id="div3">透明度</div> </body> </html>