CSS3及JS简单实现选项卡效果(适配手机端和pc端)

想要适配手机端和pc端,有几种简单的方法,本人使用的是百分比分配的方法。

*{
	padding: 0;
	margin: 0;
}
body,html{
	width: 100%;
	height: 100%;
	overflow: hidden;
}
#bottom_box{
	width: 100%;
	height: 50px;
	background-color: #eee;
	display: flex;   //这是flex布局,父元素设置为flex,子元素设置几等份就是分成几等份
	position: fixed;
	bottom: 0px;
}
.tab{
	flex:1;    //子元素都平均是1:1:1:1的意思
	text-align: center;
	padding-top:5px; 
}
img{
	width: 22px;
}
#main_container{
	width: 400%;
	height: 100%;
	overflow: hidden;
	position: relative;
	transition:left .5s ease;  //transition是css3的动画,能够平滑的过渡效果,兼容移动端
}
#box_01,#box_02,#box_03,#box_04{
	width: 25%;
	height: 100%;
	float: left;
}
#box_01{
	background-color: #ccc;
}
#box_02{
	background-color: pink;
}
#box_03{
	background-color: red;
}
#box_04{
	background-color: green;
}

<div id="main_container" style="left:0%"> <div id="box_01">01</div> <div id="box_02">02</div> <div id="box_03">03</div> <div id="box_04">04</div> </div> <div id="bottom_box"> <div id="tab_01" class="tab" style="background-color:orange" onclick="hintShow(0)"> <img src="1.png" /> <div class="tab_word_01">首页</div> </div> <div id="tab_02" class="tab" onclick="hintShow(1)"> <img src="1.png" /> <div class="tab_word_01">药箱</div> </div> <div id="tab_03" class="tab" onclick="hintShow(2)"> <img src="1.png" /> <div class="tab_word_01">购物车</div> </div> <div id="tab_04" class="tab" onclick="hintShow(3)"> <img src="1.png" /> <div class="tab_word_01">个人中心</div> </div> </div>

js代码:

var main_container=document.getElementById('main_container');
var tab_01=document.getElementById('tab_01');
var tab_02=document.getElementById('tab_02');
var tab_03=document.getElementById('tab_03');
var tab_04=document.getElementById('tab_04');

function hintShow(ele){
	if(ele==0){
		main_container.style.left="0%";
		tab_01.style.backgroundColor="orange";
		tab_02.style.backgroundColor="";
		tab_03.style.backgroundColor="";
		tab_04.style.backgroundColor="";
	}else if(ele==1){
		main_container.style.left="-100%";
		tab_01.style.backgroundColor="";
		tab_02.style.backgroundColor="orange";
		tab_03.style.backgroundColor="";
		tab_04.style.backgroundColor="";
	}else if(ele==2){
		main_container.style.left="-200%";
		tab_01.style.backgroundColor="";
		tab_02.style.backgroundColor="";
		tab_03.style.backgroundColor="orange";
		tab_04.style.backgroundColor="";
	}else if(ele==3){
		main_container.style.left="-300%";
		tab_01.style.backgroundColor="";
		tab_02.style.backgroundColor="";
		tab_03.style.backgroundColor="";
		tab_04.style.backgroundColor="orange";
	}
}

想要兼容手机端,必须在<head></head>标签中加上<meta name="viewport" content="width=device-width,initial-scale=1,max-scale=1.0">

很简单就实现了选项卡效果。

posted @ 2017-04-26 22:40  heyujun-  阅读(826)  评论(4编辑  收藏  举报