最近一直在看运动的JS特效,主要看的是原生写法,太麻烦了,最终看到写了个运动的方法,后面可以直接引用,然后发现这个方法和jQ其实差不多了,代码分别如下:
基本的HMTL和CSS
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>原生、jQ和CSS3运动模块</title> </head> <style type="text/css"> div{border: 1px solid red;margin: 20px;height: 100px;width:100px;background-color:pink;opacity:1;} </style> <body> <div id='div1'> </div> <div id='div2'> </div> <div id='div3'> </div> </body>
一、原生JS写法
//原生写法 window.onload=function(){ var div11=document.getElementById('div1'); var div21=document.getElementById('div2'); var div31=document.getElementById('div3'); div11.onmouseover=function() {startMove(div11,'height',200);}; div21.onmouseover=function() {startMove(div21,'width',200);}; div31.onmouseover=function() {startMove(div31,'opacity',100);}; div11.onmouseout=function() {startMove(div11,'height',100);}; div21.onmouseout=function() {startMove(div21,'width',100);}; div31.onmouseout=function() {startMove(div31,'opacity',30);}; }; function getStyle(obj, attr) { if(obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } } //function getStyle(obj, attr) { // return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr]; //} //运动框架 function startMove(obj, attr, iTarget) { clearInterval(obj.timer); obj.timer=setInterval(function (){ var iCur=0; if(attr=='opacity') { iCur=parseInt(parseFloat(getStyle(obj, attr))*100); } else { iCur=parseInt(getStyle(obj, attr)); } var iSpeed=(iTarget-iCur)/8; iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed); if(iCur==iTarget) { clearInterval(obj.timer); } else { if(attr=='opacity') { obj.style.filter='alpha(opacity:'+(iCur+iSpeed)+')'; obj.style.opacity=(iCur+iSpeed)/100; } else { obj.style[attr]=iCur+iSpeed+'px'; } } }, 30) }
二、jQ写法
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $().ready(function(){ $('#div1').mouseover(function(){ $(this).animate( {width:'200px'},"slow" ); }); $('#div2').mouseover(function(){ $(this).animate( {height:'200px'},"slow" ); }); $('#div3').mouseover(function(){ $(this).animate( {opacity:'1'},"slow" ); }); $('#div1').mouseout(function(){ $(this).animate( {width:'100px'},"slow" ); }); $('#div2').mouseout(function(){ $(this).animate( {height:'100px'},"slow" ); }); $('#div3').mouseout(function(){ $('#div3').animate( {opacity:'0.3'},"slow" ); }) }) </script>
三、CSS3写法
#div2{transition:height 2s 2s;} #div1{transition:width 2s;} #div3{transition: opacity 2s;-moz-transition:opacity 2s;-webkit-transition:opacity 2s;-o-transition:opacity 2s;} #div1:hover{width: 200px;} #div2:hover{height: 200px;} #div3:hover{ opacity:0; filter: alpha(opacity=0);}
对比可以看出还是CSS3方法比较合适,通过原先的学习下原理,复杂的运动模式用jQ,最优的选用CSS3(不考虑低版本IE的兼容性的情况下)。
CSS3已经支持IE10及以上的版本。