1. 程式人生 > >tab切換選項卡 (原生/jQ/vue) 實現方式

tab切換選項卡 (原生/jQ/vue) 實現方式

<!DOCTYPE >
<html>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
        <title></title>
        <style type="text/css">
            *{margin: 0; padding: 0;}
            ul{margin: 10px 20px;}
            ul li{display: inline-table
; background: #eee; padding: 10px;}
.active{background: blue; color: #fff;} #content > div{width: 200px; height: 150px; border: solid #eee 1px; display: none;} #content > div.show{display: block;}
</style> <!--JQUERY --> <script
src="jquery-1.11.2.js" type="text/javascript" charset="utf-8">
</script> <script type="text/javascript"> $(function(){ $('ul li').click(function(){ $(this).addClass('active').siblings().removeClass('active'); $("#content > div").eq($(this).index()).show().siblings().hide(); }) });
</script> <!--JavaScript --> <script type="text/javascript"> window.onload = function(){ var oLi = document.getElementsByTagName("li"); var onlyDiv = document.getElementById("content"); var oDiv = onlyDiv.getElementsByTagName("div"); for(var i = 0; i < oLi.length; i++){ oLi[i].index = i; //給點選的按鈕新增索引值 oLi[i].onclick = function(){ for(var i = 0; i < oLi.length; i++){ oLi[i].className = ""; //去掉其它按鈕高亮樣式 oDiv[i].style.display = "none"; //隱藏所有顯示區域 } this.className = "active"; oDiv[this.index].style.display = "block"; //點選的索引值傳入顯示區域的陣列 } } } </script> </head> <body> <ul> <li class="active">1</li> <li>2</li> <li>3</li> </ul> <div id="content"> <div class="show">111</div> <div >222</div> <div >333</div> </div> </body> </html>

VUE

<template> 
<li
      v-for="(item,index) in tabList" 
      :class="{'active':isActive === index}"
       @click="changeBg(index)"
   >
      {{item}}
</li>
</template>
export default {
  data () {
    return {
        tabList:['茄子','黃瓜'],
        isActive: 0 //預設第一個tab顯示
    }
  },
  methods:{
    changeBg(index){
        this.isActive = index
    }
  }
}
</script>