要点:
计算非当前元素的宽度,然后用总宽度减去,即时得到当前的宽度
设置计时器的领结点
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>手风琴效果</title> <style type="text/css"> * { padding: 0; margin: 0; } li { list-style: none; } body { background: #f6f9fc; } div { 660px; height: 254px; border: 1px solid #ccc; margin: 50px auto 0; overflow:hidden; } ul { 3300px; height: 254px; } ul li { 22px; height: 254px; float: left; position: relative; overflow:hidden; } .active { 550px; } ul span { 21px; height: 244px; padding-top: 10px; border-right: 1px solid #fff; position: absolute; top: 0; right: 0; color: #fff; font-size: 12px; text-align: center; cursor: pointer; } ul img { 550px; height: 254px; } .bg0 { background: #00FFCC; } .bg1 { background: #636363; } .bg2 { background: #3d7fbb; } .bg3 { background: #5ca716; } .bg4 { background: #f28b24; } .bg5 { background: #7c0070; } </style> <script src="dome.js"></script> </head> <body> <div id="show1"> <ul> <li class="active"> <span class="bg0">这是第一个</span> <img src="images/1.jpg" /> </li> <li> <span class="bg1">这是第二个</span> <img src="images/2.jpg" /> </li> <li> <span class="bg2">这是第三个</span> <img src="images/3.jpg" /> </li> <li> <span class="bg3">这是第四个</span> <img src="images/4.jpg" /> </li> <li> <span class="bg4">这是第五个</span> <img src="images/5.jpg" /> </li> <li> <span class="bg5">这是第六个</span> <img src="images/6.jpg" /> </li> </ul> </div> </body> </html>
dome.js
window.onload=function () { createAccordion('show1'); }; function createAccordion(id){ var oDiv = document.getElementById(id); var aLi = oDiv.getElementsByTagName('li'); var aSpan = oDiv.getElementsByTagName('span'); var iMinWidth = 9999; var i=0; oDiv.timer = null; for(i=0; i<aLi.length; i++){ aSpan[i].index = i; aSpan[i].onmouseover = function(){ gotoImg(oDiv, this.index, iMinWidth); } iMinWidth = Math.min(iMinWidth, aLi[i].offsetWidth); } } function gotoImg(oDiv, iIndex, iMinWidth){ oDiv.timer ? clearInterval(oDiv.timer) : ''; oDiv.timer = setInterval(function(){ changeWidthInner(oDiv, iIndex, iMinWidth); }, 30); } function changeWidthInner(oDiv, iIndex, iMinWidth){ var aLi = oDiv.getElementsByTagName('li'); var aSpan = oDiv.getElementsByTagName('span'); var iWidth=oDiv.offsetWidth; var bEnd = true; var w=0; var i=0; for(i=0; i<aLi.length; i++){ if(i==iIndex){ continue; } if(aLi[i].offsetWidth == iMinWidth){ iWidth -= iMinWidth; continue; } bEnd = false; var speed = Math.ceil((aLi[i].offsetWidth - iMinWidth)/5); w = aLi[i].offsetWidth - speed; if(w <= iMinWidth){ w = iMinWidth; } aLi[i].style.width = w + 'px'; iWidth -= w; } aLi[iIndex].style.width = iWidth + 'px'; bEnd ? clearInterval(oDiv.timer) : ''; }