<style> body,div,span{ margin:0; padding:0; } #div1{ width:200px; height:200px; background-color:red; position: relative; left: -200px; top:0; } #share{ width:20px;; height:50px; background-color: blue; color: white; position: absolute; left: 200px; top:75px; } </style> <div id="div1"> <span id="share">分享</span> </div>
1.速度动画
<script> window.onload=function(){ var oDiv=document.getElementById("div1"); oDiv.onmouseover=function(){ startMove(0); }; oDiv.onmouseout=function(){ startMove(-200); } }; var timer=null; function startMove(iTarget){ clearInterval(timer); var oDiv=document.getElementById("div1"); timer=setInterval(function(){ var speed=0; if(oDiv.offsetLeft<iTarget){ speed=2; }else{ speed=-2; } if(oDiv.offsetLeft==iTarget){ clearInterval(timer); }else{ oDiv.style.left=oDiv.offsetLeft + speed + 'px'; } },30); } </script>
效果如下:
初始:,鼠标移入后向右滑动:,鼠标移出后向左滑动隐藏:
2.透明度动画
<style> div{ width:200px; height:200px; background: red; filter:alpha(opacity:30); opacity:0.3; } </style> <script> window.onload = function(){ var oDiv=document.getElementById("div1"); oDiv.onmouseover=function(){ startMove(100); }; oDiv.onmouseout=function(){ startMove(30); } }; var timer=null; var alpha=30; function startMove(iTarget){ var oDiv=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ var speed = 0; if(alpha < iTarget){ speed=10; }else{ speed=-10; } if(alpha == iTarget){ clearInterval(timer); }else{ alpha+=speed; oDiv.style.opacity = alpha/100; } },30) } </script>
效果如下:
初始:,鼠标移入变不透明:,鼠标移出变透明:
3.缓冲动画,动画移动速度有渐变效果。与1速度动画有对比不同。
<script> window.onload=function(){ var oDiv=document.getElementById('div1'); oDiv.onmouseover=function(){ startMove(0); }; oDiv.onmouseout=function(){ startMove(-200); } }; var timer=null; function startMove(iTarget){ clearInterval(timer); var oDiv=document.getElementById('div1'); timer=setInterval(function(){ var speed=(iTarget-oDiv.offsetLeft)/10; speed = speed>0?Math.ceil(speed):Math.floor(speed); if(oDiv.offsetLeft==iTarget){ clearInterval(timer); }else{ oDiv.style.left=oDiv.offsetLeft + speed + 'px'; } },30) } </script>