在div里点击同一行a标签的热门商品、造型、饰品、宠物、其他、皮肤 切换不同的div页面
时间: 2023-10-01 19:06:02 浏览: 67
下面是一个简单的实现:
HTML代码:
```
<div class="category">
<a href="#" class="active" data-target="hot">热门商品</a>
<a href="#" data-target="style">造型</a>
<a href="#" data-target="accessories">饰品</a>
<a href="#" data-target="pets">宠物</a>
<a href="#" data-target="other">其他</a>
<a href="#" data-target="skins">皮肤</a>
</div>
<div class="content">
<div id="hot" class="tab active">热门商品内容</div>
<div id="style" class="tab">造型内容</div>
<div id="accessories" class="tab">饰品内容</div>
<div id="pets" class="tab">宠物内容</div>
<div id="other" class="tab">其他内容</div>
<div id="skins" class="tab">皮肤内容</div>
</div>
```
CSS代码:
```
.category {
display: flex;
}
.category a {
padding: 10px;
margin-right: 10px;
color: #333;
text-decoration: none;
}
.category a.active {
color: #f00;
}
.content .tab {
display: none;
}
.content .active {
display: block;
}
```
JavaScript代码:
```
// 获取所有的a标签
var tabs = document.querySelectorAll('.category a');
// 遍历a标签,为它们绑定点击事件
tabs.forEach(function(tab) {
tab.addEventListener('click', function(e) {
e.preventDefault(); // 阻止默认行为
// 获取目标div的id
var targetId = this.getAttribute('data-target');
// 隐藏所有的div
var divs = document.querySelectorAll('.content .tab');
divs.forEach(function(div) {
div.classList.remove('active');
});
// 显示目标div
var targetDiv = document.getElementById(targetId);
targetDiv.classList.add('active');
// 将当前a标签设为active
tabs.forEach(function(tab) {
tab.classList.remove('active');
});
this.classList.add('active');
});
});
```
在这个例子中,我们使用了CSS的display属性来控制不同的div的显示和隐藏,通过JavaScript来绑定点击事件,并且在点击事件中切换不同的div的显示和隐藏,以及设置当前a标签的状态。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)