写一个web通过按不同按钮显示不同内容
时间: 2024-02-12 07:08:40 浏览: 27
好的,我可以帮你回答这个问题。以下是一个示例,可以通过按不同的按钮显示不同的内容:
```html
<!DOCTYPE html>
<html>
<head>
<title>显示不同内容</title>
<style>
/* 样式表,用于设置按钮和内容区域的样式 */
button {
font-size: 20px;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
#content1, #content2, #content3 {
font-size: 24px;
padding: 20px;
background-color: #f2f2f2;
border-radius: 5px;
margin-top: 20px;
display: none;
}
#content1.show1, #content2.show2, #content3.show3 {
display: block;
}
</style>
</head>
<body>
<button onclick="showContent('1')">内容 1</button>
<button onclick="showContent('2')">内容 2</button>
<button onclick="showContent('3')">内容 3</button>
<div id="content1" class="show1">
这是内容 1。
</div>
<div id="content2" class="show2">
这是内容 2。
</div>
<div id="content3" class="show3">
这是内容 3。
</div>
<script>
function showContent(id) {
// 隐藏所有内容区域
document.getElementById("content1").classList.remove("show1");
document.getElementById("content2").classList.remove("show2");
document.getElementById("content3").classList.remove("show3");
// 显示指定的内容区域
document.getElementById("content" + id).classList.add("show" + id);
}
</script>
</body>
</html>
```
在这个示例中,我们创建了三个按钮和三个内容区域。默认情况下,内容区域都被设置为`display: none`,以隐藏它们。当用户点击按钮时,它将调用`showContent()`函数来切换内容区域的显示。该函数将会首先将所有内容区域的类名中的显示类移除,然后将指定内容区域的类名中的显示类添加。这将会通过 CSS 将其显示出来。
在这个示例中,我们并没有在 Web 加载时显示任何内容。如果您想要在 Web 加载时默认显示某个内容区域,可以在`showContent()`函数中添加一个条件来显示默认内容。例如,您可以添加以下代码来在 Web 加载时默认显示内容 1:
```javascript
if (id === '1') {
document.getElementById("content1").classList.add("show1");
}
```
相关推荐
![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)