html实现类似android的tab切换页面

本文介绍了一种实现移动端Tab切换页面的方法,通过隐藏和显示的技巧来切换不同的子页面div,无论页面中添加多少内容都不会影响切换效果。讨论了在使用Android WebView时获取宽度的不准确性,并提出了在页面加载完成后获取宽度的方法。最后邀请有经验的开发者提供更合理的方法以供学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:初学html,css,js。想做一个类似于android的tab切换的页面,从网上找了好多例子,只不过一旦子页面的div中加上一个div就起不到切换的效果了,所以一急之下,自己 根据隐藏,显示的方法,写了一个类似androidtab切换页面的例子,个人也不清楚这样做合不合理,写此篇文章一个是希望对新手童鞋有个启发,同时也希望知道怎么实现合 理的大大给我留言,让我能学习到更靠谱的方法(我这个是主要用在移动端的)。勿喷。不多说了,内容比较简单,直接贴代码:

html代码:

<body onload="loadon()">
<div id="mybody" class="mybody">
	<div id="centertab" class="centertab">
		<div onclick="onleft()" id="left" class="left">left</div>
		<div onclick="onright()" id="right" class="right">right</div>
	</div> 
</div>

<div id="parent1"> 页面一</div>

<div id="parent2" style="display:none">页面二</div>

</body>



这种实现方法,在parent1和parent2中添加任何内容都可以,包括div,都不会影响到切换的效果。可能就是界面一开始加载的时候内容多,如果内容太多可能会影响用户体验。


CSS代码:

<style type="text/css">


body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, button, textarea, p, blockquote, th, td { margin: 0; padding: 0;}

.mybody{
	width:100%; 
	height:50px; 
	background-color:#000; 
	margin:0 auto;
}

.centertab{
	width:200px; 
	margin:auto auto;
}

.left{
	width:98px;
	 height:24px; 
	 float:left; 
	 background-color:#999; 
	 text-align:center; 
	 line-height:24px; 
	 color:#000; 
	 border:1px solid #999;
}

.right{
	width:98px; 
	height:24px; 
	float:left; 
	background-color:#000; 
	text-align:center; 
	line-height:24px;
	 color:#FFF; 
	 border:1px solid #999;	
}

</style>


js代码:

<script type="text/javascript">
function loadon(){
	var screenWidth = document.body.clientWidth;//获取body可见的宽度
	document.getElementById("left").style.marginTop = 13+"px";
	document.getElementById("right").style.marginTop = 13+"px";
}
	
function onleft(){
	document.getElementById("parent2").style.display = "none";
	document.getElementById("parent1").style.display = "block";
	document.getElementById("left").style.backgroundColor="#999999";
	document.getElementById("left").style.color="#000000";
	document.getElementById("right").style.backgroundColor="#000000";
	document.getElementById("right").style.color="#ffffff";
}
	
function onright(){
	document.getElementById("parent2").style.display = "block";
	document.getElementById("parent1").style.display = "none";
	document.getElementById("left").style.backgroundColor="#000000";
	document.getElementById("left").style.color="#ffffff";
	document.getElementById("right").style.backgroundColor="#999999";
	document.getElementById("right").style.color="#000000";
}
</script>


这里的onload方法在android的webview中用的时候获取的宽度有时候会不准,可以在webview加载完成是调用获取的方法比较靠谱。

希望有好方法实现的大大多多留言,指导指导。拜谢!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值