<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>8 任意值属性 透明度</title> <style> body,div{ padding:0; margin:0; } #div1{ width:200px; height:200px; background-color:yellow; border:4px solid #000; opacity: 0.3; } </style> <script> window.onload=function(){ var oDiv = document.getElementById('div1'); oDiv.onmousemove = function(){ startMove(oDiv,'opacity',100); }; oDiv.onmouseout = function(){ startMove(oDiv,'opacity',30); } }; function startMove(obj,attr,iTarget){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var icur = null; //属性值 变量 if(attr == 'opacity'){ icur = Math.round(parseFloat(getStyle(obj,attr))*100); }else{ icur = parseInt(getStyle(obj,attr)); } var speed = (iTarget - icur)/8; // 速度 变速 speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if(icur == iTarget){ //变量变化 clearInterval(obj.timer); }else{ if(attr == 'opacity'){ obj.style.opacity = (icur + speed)/100; }else{ obj.style[attr] = icur + speed + 'px'; } } },30) } function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; } else{ return getComputedStyle(obj,false)[attr]; } } </script> </head> <body> <div id="div1"></div> </body> </html>