js语言,单击同学,家人,朋友任意一项,如果当前是收缩,则展开,同时,其余项收缩,如果当前展开,则收缩
时间: 2023-11-16 16:06:52 浏览: 48
这是一个比较常见的需求,可以通过以下步骤实现:
1. 给同学、家人、朋友三个按钮分别绑定点击事件。
2. 在点击事件中,判断当前按钮的状态,如果是展开,则将其收缩,同时将其他按钮也收缩;如果是收缩,则将其展开,同时将其他按钮也收缩。
3. 可以通过添加 CSS 类来改变按钮的状态,比如添加一个 `.active` 类表示当前按钮是展开的状态。
下面是一个简单的示例代码:
HTML:
```
<button class="btn" data-type="classmate">同学</button>
<button class="btn" data-type="family">家人</button>
<button class="btn" data-type="friend">朋友</button>
<div class="content classmate">
同学的内容
</div>
<div class="content family">
家人的内容
</div>
<div class="content friend">
朋友的内容
</div>
```
CSS:
```
.btn {
background-color: #eee;
border: none;
padding: 10px;
margin-right: 10px;
cursor: pointer;
}
.btn.active {
background-color: #ccc;
}
.content {
display: none;
}
```
JavaScript:
```
const btns = document.querySelectorAll('.btn');
const contents = document.querySelectorAll('.content');
btns.forEach(btn => {
btn.addEventListener('click', () => {
const type = btn.dataset.type;
if (btn.classList.contains('active')) {
btn.classList.remove('active');
contents.forEach(content => {
if (content.classList.contains(type)) {
content.style.display = 'none';
}
});
} else {
btns.forEach(otherBtn => {
otherBtn.classList.remove('active');
});
contents.forEach(content => {
content.style.display = 'none';
});
btn.classList.add('active');
contents.forEach(content => {
if (content.classList.contains(type)) {
content.style.display = '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)