JS实现选项卡切换

   下面是用JS简单地实现选项卡功能的实例。

  注意点:(1)闭包后,要使用立即执行函数;

                (2)绑定事件注意参数;

                (3)思路:将当前div显示,其余隐藏,给button绑定事件,触碰后显示相应内容。

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>选项卡练习</title>
		<!--CSS样式-->
		<style type="text/css">
			.wrapper {
				box-shadow: -2px 0 5px lightsteelblue, 0 -2px 5px lightsteelblue, 0 2px 5px lightsteelblue, 2px 0 5px lightsteelblue;
				height: 450px;
				width: 533px;
			}
			
			.content {
				display: none;
				width: 530px;
				height: 395px;
				margin-top: 8px;
				box-shadow: -2px 0 5px gray, 0 -2px 5px gray, 0 2px 5px gray, 2px 0 5px gray;
			}
			/*点击该按钮的时候显示该颜色*/
			
			.active {
				background-color: lightsteelblue;
			}
			
			button {
				background-color: lightseagreen;
				margin-top: 5px;
				list-style-type: none;
				width: 125px;
				height: 40px;
				font-family: "新宋体";
				font-size: 18px;
				border: none;
				box-shadow: -2px 0 5px lightsteelblue, 0 -2px 5px lightsteelblue, 0 2px 5px lightsteelblue, 2px 0 5px lightsteelblue;
			}
			
			button:first-child {
				margin-left: 10px;
			}
		</style>
	</head>

	<body>
		<!--布局样式-->
		<div class="wrapper">
			<!--选项卡-->
			<button class="active">选项卡一</button>
			<button>选项卡二</button>
			<button>选项卡三</button>
			<button>选项卡三</button>
			<div class="content" style="display: block;">
				<img src="img/pic-one.png" />
			</div>
			<div class="content">
				<img src="img/pic-two.png" />
			</div>
			<div class="content">
				<img src="img/pic-three.png" />
			</div>
			<div class="content">
				<img src="img/pic-fou.png" />
			</div>
		</div>
		<!--JS代码-->
		<script type="text/javascript">
			// 将按钮和盒子拿出来
			var btn = document.getElementsByTagName('button');
			var div = document.getElementsByClassName('content');
			// 每一个button上面绑定事件
			for(var n = 0; n < btn.length; n++) {
				//生成闭包的立即函数
				(function(i) {
					btn[n].onclick = function() {
						for(var m = 0; m < btn.length; m++) {
							btn[m].className = ""; //清空效果
							div[m].style.display = "none";
						}
						//当前点击的button设置变化
						this.className = "active";
						div[i].style.display = "block";
					}
				}(n))
			}
		</script>
	</body>
</html>

 演示效果:


                                                                                                                                                           元气少女,加油! 

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值