js實現手風琴效果

來源:互聯網
上載者:User

標籤:設定   i++   css   rip   out   length   obj   擷取   padding   

之前在慕課網上有練習手風琴效果,但是老師使用jquery簡簡單單的兩三行實現了,今天自己用js練習一下效果

    <div id="divbox">        <ul>            <li class="pic1"><a href="javascript:;">床頭明月光</a></li>            <li class="pic2"><a href="javascript:;">疑似地上霜</a></li>            <li class="pic3"><a href="javascript:;">舉頭望明月</a></li>            <li class="pic4"><a href="javascript:;">低頭思故鄉</a></li>        </ul>    </div>
*{padding: 0;margin: 0;list-style: none}#divbox{    width: 1000px;}ul{    width: 1000px;    height: 300px;}ul li{    height: 300px;    float: left;/*     width: 100px; */}ul li a{    text-decoration: none;    color:#666;    width: 100px;    height: 300px;    line-height: 300px;    text-align: center;    display: block;    background-color:#fff;    opacity: 0.3;}.pic1{    background: url(‘1.png‘);}.pic2{    background: url(‘2.png‘);}.pic3{    background: url(‘3.png‘);}.pic4{    background: url(‘4.png‘);}.active{    width: 700px;}</style>

js代碼:

var lis=document.getElementsByTagName(‘li‘);   //擷取document中的所有li/*animate動畫*/function ani(obj){    timer=setInterval(function(){    //設定定時器        var speed=10;        if(parseInt(obj.style.width)<700){     //如果傳入的對象的寬小於700px            obj.style.width=parseInt(obj.style.width)+speed+‘px‘;   //讓當前寬加speed            speed+=10;    //每執行一次定時器,speed+10        }else{            return;        }    },20);  20ms執行一次定時器}for(var i=0;i<lis.length;i++){   //遍曆li數組    lis[i].index=i;         //迴圈把i的值賦值給li的index    var timer;    lis[i].onmouseover=function(){        for(var i=0;i<lis.length;i++){            lis[i].style.width=‘100px‘;    //當滑鼠移入到某個li時,遍曆迴圈數組,把所有li的寬都設定為100px        }        ani(lis[this.index]);  //使用ani方法,把滑鼠移入的li的寬值變為700px    }    lis[i].onmouseout=function(){             lis[this.index].style.width=‘100px‘;       //滑鼠移出時,把當前li的寬設定回100px        clearInterval(timer);      //清除定時器    }}

這樣就能實現手風琴效果了,但是還有一點點bug,因為li初始化的時候寬度是100px,當滑鼠移入li時,li會變為700px,但是滑鼠移開時不會按700px的寬度,仍然以100px的寬為準。如果有知道這個問題的小夥伴請大家多多指教指教。

如果想要背景圖片,請到本人相簿下載。

js實現手風琴效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.