怎么写出个web可以通过点击不同按钮切换不同内容
时间: 2023-09-08 14:08:47 浏览: 161
你可以使用HTML、CSS和JavaScript来实现这个功能。首先,你需要编写HTML代码,创建一个包含不同内容的容器。然后,你可以为每个按钮创建一个事件监听器,当按钮被点击时,它会显示对应的内容,并隐藏其他内容。以下是一个简单的示例:
HTML代码:
```
<div id="content-container">
<div id="content1">这是内容1</div>
<div id="content2">这是内容2</div>
<div id="content3">这是内容3</div>
</div>
<button id="btn1">内容1</button>
<button id="btn2">内容2</button>
<button id="btn3">内容3</button>
```
CSS代码:
```
#content-container div {
display: none;
}
#content-container div.active {
display: block;
}
```
JavaScript代码:
```
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");
var content1 = document.getElementById("content1");
var content2 = document.getElementById("content2");
var content3 = document.getElementById("content3");
btn1.addEventListener("click", function() {
content1.classList.add("active");
content2.classList.remove("active");
content3.classList.remove("active");
});
btn2.addEventListener("click", function() {
content1.classList.remove("active");
content2.classList.add("active");
content3.classList.remove("active");
});
btn3.addEventListener("click", function() {
content1.classList.remove("active");
content2.classList.remove("active");
content3.classList.add("active");
});
```
这个示例包含三个内容和三个按钮。当一个按钮被点击时,它添加一个“active”类到对应的内容div,并从其他内容div中删除这个类。CSS中的“active”类设置了显示属性为“block”,这样它就会显示在页面上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)