純JS制作選項卡--JavaScript實例集錦(初學)
阿新 • • 發佈:2018-02-02
不用 () body tel bsp classname nload html spl
最近重新從最基礎學習JavaScript,如同蓋房,先要打好基礎,一磚一瓦都很重要。
下面我來嘚吧幾句,附上從書上學到的實例與效果。
JS可以用面向過程去寫,也可以使用面向對象。面向對象會使一段JS代碼更好進行復用,封裝與繼承。
已下我會寫出2種實現tab切換的方法--面向過程與面向對象
面向過程如同你寫一篇文章,從頭寫到尾,不用介紹人物,場景,按照順序一路寫下去即可。
1.tab切換效果圖
代碼實現:
<!DOCTYPE html> <html> <head> <title>選項卡</title> <styletype="text/css"> input{background: white;} .active{background: yellow;} div{width: 200px;height: 200px;background: #ccc;display: none;} </style> <script type="text/javascript"> window.onload=function(){ var aBtn=document.getElementsByTagName(‘input‘);//getElementByTagName 獲取所有的input var aDiv=document.getElementsByTagName(‘div‘);//getElementByTagName 獲取所有的div
for(var i=0;i<aBtn.length;i++){
aBtn[i].index=i; //記錄按鈕的索引值,點擊了第幾個按鈕
aBtn[i].onclick=function(){
for (var i = 0;i<aBtn.length;i++) {
aBtn[i].className=""; //for循環設置其他按鈕的Class為空
aDiv[i].style.display="none";//for循環設置其他div隱藏
}
// alert(‘點擊了第‘+this.index+‘個按鈕‘);
this.className="active";//設置當前按鈕的Class為active
aDiv[this.index].style.display="block";//設置當前div顯示
};
}
}
</script>
</head>
<body>
<input class="active" type="button" value="1"/>
<input type="button" value="2"/>
<input type="button" value="3"/>
<div style="display: block">111</div>
<div>222</div>
<div>333</div>
</body>
</html>
2.面向對象的tab切換
效果圖一樣,但代碼實現會有差別
代碼實現:
<!DOCTYPE html> <html> <head> <title>選項卡</title> <style type="text/css"> input{background: white;} .active{background: yellow;} #div1 div{width: 200px;height: 200px;background: #ccc;display: none;} #div1{display: block;} </style> <script type="text/javascript"> // var aBtn=null; // var aDiv=null; window.onload=function(){ var oTab=new TabSwitch(‘div1‘);//實例化一個對象 } function TabSwitch(id){ var oDiv=document.getElementById(id); this.aBtn=oDiv.getElementsByTagName(‘input‘); this.aDiv=oDiv.getElementsByTagName(‘div‘); var _this=this;//用_this存取對象,對象具有標簽切換的功能 for(var i=0;i<this.aBtn.length;i++){ this.aBtn[i].index=i; this.aBtn[i].onclick=function() { _this.tab(this); }; } }; TabSwitch.prototype.tab=function(oBtn){ for (var i = 0;i<this.aBtn.length;i++) { this.aBtn[i].className=""; this.aDiv[i].style.display="none"; } // alert(‘點擊了第‘+this.index+‘個按鈕‘); oBtn.className="active"; this.aDiv[oBtn.index].style.display="block"; }; </script> </head> <body> <div id="div1"> <input class="active" type="button" value="1"/> <input type="button" value="2"/> <input type="button" value="3"/> <div style="display: block">111</div> <div>222</div> <div>333</div> </div> </body> </html>
面向對象的好處是:如果想多次使用該JS方法,只需要實例化多個對象即可。
var oTab=new TabSwitch(‘div1‘);//實例化一個對象
var oTab=new TabSwitch(‘div2‘);//實例化一個對象
純JS制作選項卡--JavaScript實例集錦(初學)