点击不同按钮切换不同div

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			button{
				
				float: left;
			}
			div{
				position: absolute;
				top: 40px;
				width: 100px;
				height: 100px;
				
				border: 1px solid red;
				float: left;
			}
			#div1{
				background-color: darkgray;
				
			}
			#div2{
				background-color: darksalmon;
			
			}
			#div3{
				background-color: darkseagreen;
				
			}
		</style>
	</head>
	<body>
		<button type="button" onclick="showDiv('div1')">btn1</button>
		<button type="button" onclick="showDiv('div2')">btn2</button>
		<button type="button" onclick="showDiv('div3')">btn3</button>
		
		
		
		<div id="div1">
			
		</div>
		<div id="div2">
			
		</div>
		<div id="div3">
			
		</div>
		<script type="text/javascript">
			let divs=document.querySelectorAll('div');
			let showDiv=(str)=>{
				for(let div of divs){
					div.style.display="none";
				}
				document.getElementById(str).style.display = "block";
			}
			
			
		</script>
	</body>
</html>

可以使用CSS和JavaScript来实现。 首先,我们需要在HTML中创建按钮和内容。例如: ```html <button class="tab-button active" data-tab="tab1">Tab 1</button> <button class="tab-button" data-tab="tab2">Tab 2</button> <div class="tab-content active" id="tab1"> This is the content for tab 1. </div> <div class="tab-content" id="tab2"> This is the content for tab 2. </div> ``` 然后,我们可以使用CSS来控制按钮和内容的显示和隐藏。例如: ```css .tab-button { background-color: #ccc; color: #fff; cursor: pointer; padding: 10px; border: none; border-radius: 5px; } .tab-button.active { background-color: #333; } .tab-content { display: none; } .tab-content.active { display: block; } ``` 最后,我们需要使用JavaScript来添加按钮点击事件,并在点击切换内容。例如: ```javascript const buttons = document.querySelectorAll('.tab-button'); const contents = document.querySelectorAll('.tab-content'); buttons.forEach((button) => { button.addEventListener('click', () => { const tab = button.dataset.tab; buttons.forEach((b) => { b.classList.remove('active'); }); contents.forEach((c) => { c.classList.remove('active'); }); button.classList.add('active'); document.getElementById(tab).classList.add('active'); }); }); ``` 这段代码会选中所有的按钮和内容,并为每个按钮添加了一个点击事件,当点击时,它会获取该按钮对应的内容的ID,然后将所有的按钮和内容的active类都删除,并将当前点击按钮和对应的内容添加active类,从而实现了切换不同内容的效果。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值