js实现选项卡
(一)思路:
選項卡就是點擊按鈕切換到相應內容,其實就是點擊按鈕把內容通過display(block none)來實現切換的。
1、首先獲取元素。
2、for循環歷遍按鈕元素添加onclick 或者 onmousemove事件。
3、因為點擊當前按鈕時會以高亮狀態顯示,所以要再通過for循環歷遍把所有的按鈕樣式設置為空和把所有DIV的display設置為none。
4、把當前按鈕添加樣式,把當前DIV顯示出來,display設置為block。
注:給多個元素添加多個事件要用for循環歷遍。如選項卡是點擊切換,當前按鈕高度,點擊和按鈕高亮就是2個事件,所以要用2個for循環歷遍。
?
HTML代碼:
<div id="box">
<input type="button" value="1" />
<input type="button" value="2" />
<input type="button" value="3" />
<input type="button" value="4" />
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
?
CSS代碼:
?
?
?
?
Javascript代碼:
<script>
window.οnlοad=function()
{
var box=document.getElementById('box');
var input=box.getElementsByTagName('input');
var div=box..getElementsByTagName('div');
for(var i=0;i<input.length;i++)
{ //循環歷遍onclick事件
input[i].index=i; //input[0].index=0 index是自定義屬性
input[i].οnclick=function(){
for(var i=0;i<input.length;i++)
{ //循環歷遍去掉button樣式和把div隱藏
input[i].className='';
div[i].style.display='none';
};
this.className='active'; //當前按鈕添加樣式
div[this.index].style.display='block'; //div顯示 this.index是當前div 即div[0]之類的
};
};
};
</script>
轉載于:https://www.cnblogs.com/wfaceboss/p/5950227.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
- 上一篇: iOS 最全面试题
- 下一篇: IBM公布Kitura 1.0和Blue