js實現的側邊欄展開收縮效果

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   java   for   

原文地址:http://www.softwhy.com/forum.php?mod=viewthread&tid=12246

<!DOCTYPE html><html><head><meta charset=" utf-8"><title>側邊欄展開收縮</title><style type="text/css">#thediv{  width:150px;  height:200px;  background:#999999;  position:absolute;  left:-150px;//div初始位置}span{  width:20px;  height:100px;  line-height:23px;  background:#09C;  position:absolute;  right:-20px;  top:70px;}</style><script>window.onload=function(){  var odiv=document.getElementById(‘thediv‘);  odiv.onmouseover=function (){startmove(0,10);}  odiv.onmouseout=function (){startmove(-150,-10);}}var timer=null;function startmove(target,speed){  var odiv=document.getElementById(‘thediv‘);  clearInterval(timer);  timer=setInterval(function (){    if(odiv.offsetLeft==target){      clearInterval(timer);    }    else{          odiv.style.left=odiv.offsetLeft+speed+‘px‘;    }  },30)}</script></head><body><div id="thediv"><span>側邊欄展開收縮</span></div></body></html>

以上代碼實現了我們的要求,滑鼠懸浮於側邊欄可以實現展開,離開實現收縮功能,下面介紹一下實現過程。
一.代碼注釋:
1.window.onload=function(){},文檔結構內容完全載入完畢再去執行函數中的代碼。
2.var odiv=document.getElementById(‘thediv‘),擷取指定元素對象。
3.odiv.onmouseover=function (){startmove(0,10);},為odiv對象註冊onmouseover事件處理函數。
4.odiv.onmouseout=function (){startmove(-150,-10);},為odiv對象註冊onmouseout事件處理函數。
5.var timer=null,聲明一個timer作為定時器函數的標識。
6.function startmove(target,speed){}此函數是展開和摺疊的核心函數,第一個參數是left的目標值,speed是速度。
7. var odiv=document.getElementById(‘thediv‘),擷取元素對象。
8.clearInterval(timer),停止前一個定時器函數的執行,可以防止多個定時器函數同時執行造成幹擾。
9.timer=setInterval(function (){},30),每隔30毫秒執行一次函數。
10.if(odiv.offsetLeft==target){clearInterval(timer);},如果div元素距離body左邊緣等於規定的尺寸,就停止定時器函數。
11.else{odiv.style.left=odiv.offsetLeft+speed+‘px‘;},否則繼續設定left屬性值。
二.相關閱讀:
1.onmouseover事件可以參閱javascript的onmouseover事件一章節。 
2.onmouseout事件可以參閱javascript的onmouseout事件詳解一章節。 
3.clearInterval()函數可以參閱window對象的clearInterval()方法一章節。 
4.setInterval()函數可以參閱setInterval()函數用法詳解一章節。 
5.offsetLeft屬性可以參閱js的offsetTop好offsetLeft屬性用法詳解一章節。

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.