选项卡(代码精简版)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>选项卡简单</title>
		<style>
			/* css样式 */
			button {
				width: 100px;
				height: 100px;
			}

			/* 按钮样式 */
			#contens {
				width: 300px;
				height: 300px;
			}

			/* 内容外围样式 */
			#contens div {
				width: 400px;
				height: 300px;
				line-height: 300px;
				text-align: center;
			}

			/* 内容外围中的div内容样式 */
		</style>
	</head>
	<body>
		<button style="background-color: antiquewhite;" class="one">按钮1</button>
		<button style="background-color: #fff;" class="two">按钮2</button>
		<button style="background-color:  #fff;" class="ther">按钮3</button>
		<button style="background-color:  #fff;" class="four">按钮4</button>
		<div id="contens">
			<div class="con" id="con1" style="display: block; background-color:antiquewhite;">
				<p>内容1</p>
			</div>
			<div class="con" id="con2" style="display: none; background-color: cadetblue;">
				<p>内容2</p>
			</div>
			<div class="con" id="con3" style="display: none; background-color: blue;">
				<p>内容3</p>
			</div>
			<div class="con" id="con4" style="display: none; background-color: aquamarine;">
				<p>内容4</p>
			</div>
		</div>
	</body>
	<script>
		let cons = document.getElementsByClassName('con');
		// 获取所有class为con的元素,即内容div标签
		console.log(cons);

		let buttons = document.getElementsByTagName('button');
		// 获取所有button按钮标签
		for (let i = 0; i < buttons.length; i++) {
			// 给每个按钮绑定点击事件
			buttons[i].onclick = function() {
				console.log(i);
				// 打印当前按钮的下标

				for (let j = 0; j < cons.length; j++) {
					buttons[j].style.backgroundColor = 'white';
					// 将所有按钮的背景颜色设为白色
					console.log(cons[j]);
					// 打印对应下标的内容div元素
					cons[j].style.display = 'none';
					// 将所有内容div元素隐藏
				}

				buttons[i].style.backgroundColor = 'yellow';
				// 将当前按钮的背景颜色设为黄色
				cons[i].style.display = 'block';
				// 将对应下标的内容div元素显示
			}
		}
	</script>
</html>

这段代码实现了一个简单的选项卡功能。点击不同按钮时,对应的内容div显示,其他内容div隐藏。按钮点击时背景颜色变为黄色,其他按钮背景颜色变为白色。

代码中先获取了所有class为"con"的内容div元素和所有button按钮元素。然后对每个按钮绑定了点击事件,点击时会遍历所有按钮和内容div元素,将所有按钮背景颜色设为白色,并隐藏所有内容div元素。然后将当前按钮背景颜色设为黄色,对应的内容div元素显示出来。

可以根据需要修改按钮的样式和内容div的样式来美化选项卡的外观。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值