我需要使用两个不同的按钮在同一部分的两个div之间切换,每个div都连接到一个按钮。
示例:(我需要每当“ btn1”处于活动状态时,“ div1”都是可见的。当我单击“ btn2”时,“ div2”是可见的而不是“ div1”,反之亦然!帮助吗?
* {
color: #fff;
}
.btn {
width: 100px;
height: 50px;
background: rgba(0,0,0,0.4);
display: inline-block;
}
.btn-active {
background: rgba(0,0,0,1);
}
.div {
width: 200px;
height: 100px;
background: red;
display: none;
}
.div-active {
display: block;
}
<div>
<div class="btn btn-active" id="btn1">
BUTTON 1
</div>
<div class="btn" id="btn2">
BUTTON 2
</div>
</div>
<div>
<div class="div div-active" id="div1">
DIV 1
</div>
<div class="div" id="div2">
DIV 2
</div>
</div>
答案 0 :(得分:0)
我建议您首先将所有按钮和div分组为两个集合。从这里,我将向每个按钮添加一个事件侦听器。该侦听器将首先删除所有 typo3-cms-blahblah
类,然后将div-active
类重新应用于相应的div。
在以下示例中可以看到:
div.active
const buttons = document.getElementsByClassName('btn');
const divs = document.getElementsByClassName('div');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
for (let i = 0; i < divs.length; i++) {
divs[i].classList.remove('div-active');
}
divs[i].classList.add('div-active');
});
}
* {
color: #fff;
}
.btn {
width: 100px;
height: 50px;
background: rgba(0, 0, 0, 0.4);
display: inline-block;
}
.btn-active {
background: rgba(0, 0, 0, 1);
}
.div {
width: 200px;
height: 100px;
background: red;
display: none;
}
.div-active {
display: block;
}
答案 1 :(得分:0)
尝试这样的事情:
<div>
<div class="btn btn-active" id="btn1">
BUTTON 1
</div>
<div class="btn" id="btn2">
BUTTON 2
</div>
</div>
<div>
<div class="div " id="div1">
DIV 1
</div>
<div class="div div-active" id="div2">
DIV 2
</div>
</div>
<script>
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
//
btn1.addEventListener("click", function(){
btn1.classList.remove("btn-active");
btn2.classList.add("btn-active");
div2.classList.remove("div-active");
div1.classList.add("div-active");
});
//
btn2.addEventListener("click", function(){
btn2.classList.remove("btn-active");
btn1.classList.add("btn-active");
div1.classList.remove("div-active");
div2.classList.add("div-active");
});
</script>