弹性菜单
/**弹性菜单的目标点的获得:
* 目标点不是确定的,其实就是当前li的位置**/
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> 3 4 <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <title>5.弹性菜单</title> 8 <meta name="author" content="Administrator" /> 9 <!-- Date: 2014-12-13 --> 10 <style> 11 *{margin:0;padding:0;font-size:13px;font-family:microsoft yahei} 12 ul{margin:40px auto;position:relative} 13 li{list-style:none;float:left;width:130px;height:30px;text-align:center;line-height:30px;} 14 li.box{margin:0 3px;background:#DE4465;} 15 #mask{position:absolute;background:#2272BD; top:0;opacity:0.5;margin:0} 16 </style> 17 <script> 18 /**弹性菜单的目标点的获得: 19 * 目标点不是确定的,其实就是当前li的位置**/ 20 window.onload=function(){ 21 var oUl=document.getElementsByTagName('ul')[0]; 22 var aLi=getByClassName(oUl,'li','box'); 23 var oMask=document.getElementById('mask'); 24 var arr=[]; 25 var timer=null; 26 var timer2=null; 27 var iSpeed=0; 28 29 30 oUl.style.width = (aLi.length)*( aLi[0].offsetWidth + 6 ) +'px'; 31 oUl.style.margin = '40px auto' 32 oMask.style.left = aLi[0].offsetLeft + 'px'; 33 34 35 36 for(var i=0;i<aLi.length;i++){ 37 38 aLi[i].onmouseover=function(){ 39 clearInterval( timer2 );//清除timer2,让oMask不回到0 40 bonce(this.offsetLeft); 41 } 42 43 //当oMask运动到当前li上的时候,鼠标已经离开了li了 44 aLi[i].onmouseout=function(){ 45 timer2=setTimeout(function(){//加一个延时定时器,让 oMask 不立即回到0 46 bonce(0) 47 },100) 48 } 49 50 //在0 - 100 毫秒内,当鼠标在oMask上面的时候,关闭 延时定时器,那么oMask就不会回到0了 51 oMask.onmouseover=function(){ 52 clearInterval( timer2 ) 53 } 54 55 //当鼠标离开oMask后,再让oMask回到0 56 oMask.onmouseout=function(){ 57 timer2=setTimeout(function(){//加一个延时定时器,让 oMask 不立即回到0 58 bonce(0); 59 },100) 60 document.title= aLi[0].offsetLeft +'-'+ oMask.offsetLeft 61 62 } 63 64 65 } 66 67 console.log(arr) 68 69 function bonce(iTarget){ 70 71 clearInterval(timer); 72 timer=setInterval(function(){ 73 iSpeed += (iTarget - oMask.offsetLeft)/6; 74 iSpeed *= 0.75; 75 if( Math.abs( iSpeed ) <= 1 && Math.abs( iTarget - oMask.offsetLeft ) <= 1 ){ 76 clearInterval(timer); 77 78 oMask.style.left = iTarget +'px'; 79 iSpeed = 0; 80 }else{ 81 oMask.style.left = oMask.offsetLeft + iSpeed +'px' 82 } 83 },30) 84 } 85 86 87 } 88 89 90 /**通过class来获取元素**/ 91 function getByClassName(oParent,tagName,className){ 92 var arr=[]; 93 var als=oParent.getElementsByTagName(tagName); 94 for(var i=0;i<als.length;i++){ 95 var a1=als[i].className.split(' '); 96 for(var j=0;j<a1.length;j++){ 97 if(a1[j]==className){ 98 arr.push(als[i]); 99 break; 100 } 101 } 102 } 103 return arr 104 } 105 </script> 106 </head> 107 <body> 108 <ul> 109 <li id="mask"></li> 110 <li class="box">首页</li> 111 <li class="box">学员</li> 112 <li class="box">课程</li> 113 <li class="box">关于</li> 114 <li class="box">留言</li> 115 <li class="box">论坛</li> 116 </ul> 117 </body> 118 </html>