html中点击左边菜单右边内容切换
时间: 2024-02-17 19:12:48 浏览: 191
在 HTML 中,实现左侧菜单和右侧内容的切换可以使用 JavaScript 和 CSS。一种常见的实现方式是使用一个包含菜单和内容的容器,然后通过 CSS 将菜单和内容分别放在左右两个 DIV 中,并使用绝对定位使它们重叠。然后通过 JavaScript 监听菜单项的点击事件,根据点击的菜单项,切换右侧内容的显示和隐藏。
以下是示例代码:
HTML:
```
<div class="container">
<div class="menu">
<ul>
<li><a href="#" id="menu1">菜单1</a></li>
<li><a href="#" id="menu2">菜单2</a></li>
<li><a href="#" id="menu3">菜单3</a></li>
</ul>
</div>
<div class="content">
<div id="content1">内容1</div>
<div id="content2">内容2</div>
<div id="content3">内容3</div>
</div>
</div>
```
CSS:
```
.container {
position: relative;
width: 100%;
height: 500px;
}
.menu {
position: absolute;
top: 0;
left: 0;
width: 20%;
height: 100%;
background-color: #ccc;
}
.content {
position: absolute;
top: 0;
left: 20%;
width: 80%;
height: 100%;
}
.content > div {
display: none;
}
.content > div.active {
display: block;
}
```
JavaScript:
```
var menu1 = document.getElementById("menu1");
var menu2 = document.getElementById("menu2");
var menu3 = document.getElementById("menu3");
var content1 = document.getElementById("content1");
var content2 = document.getElementById("content2");
var content3 = document.getElementById("content3");
menu1.onclick = function() {
content1.classList.add("active");
content2.classList.remove("active");
content3.classList.remove("active");
}
menu2.onclick = function() {
content1.classList.remove("active");
content2.classList.add("active");
content3.classList.remove("active");
}
menu3.onclick = function() {
content1.classList.remove("active");
content2.classList.remove("active");
content3.classList.add("active");
}
```
这段代码中,我们首先获取菜单项和内容的 DOM 元素,然后通过 onclick 事件监听菜单项的点击事件。在事件处理函数中,我们根据点击的菜单项,将对应的内容 DIV 元素添加 active 类,使其显示出来,同时将其他内容 DIV 元素的 active 类移除,使其隐藏。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)