我有这个代码按照我想要的方式运行,只是我不希望有人能够打开多个"选项卡";一次。我不知道如何让Javascript删除";变换有效";如果通过单击按钮将其添加到另一个div中,则从当前拥有它的div中初始化。
function Slidein(num) {
var element = document.getElementById(num);
element.classList.toggle("transform-active");
}
.tabcontent {
background-color: #218D9B;
overflow: hidden;
height: 0px;
width: 600px;
}
.transform{
-webkit-transition: .7s;
-moz-transition: .7s;
-o-transition: .7s;
-ms-transition: .7s;
transition: .7s;
}
.transform-active {
background-color: #45CEE0;
height: 200px;
width: 600px;
visibility: visible;
}
<button id="button1" onclick="Slidein('div1')">Button 1</button>
<button id="button2" onclick="Slidein('div2')">Button 2</button>
<button id="button3" onclick="Slidein('div3')">Button 3</button>
<div id="div1" class="tabcontent transform">
Here's some text in my FIRST div
</div>
<div id="div2" class="tabcontent transform">
This would be the SECOND div text
</div>
<div id="div3" class="tabcontent transform">
And now we have a THIRD div with its text
</div>
也许可以将Slidein更改为以下内容:
function Slidein(num) {
var elementWithTransformActiveClass = document.querySelector('.transform-active');
var element = document.getElementById(num);
if (!!elementWithTransformActiveClass) elementWithTransformActiveClass.classList.remove("transform-active");
if (element !== elementWithTransformActiveClass) element.classList.add("transform-active");
}
编辑:
您可以访问活动按钮:
var buttonId = num.replace('div', 'button');
var button = document.getElementById(buttonId);
// and now you can add a new class to the button
button.classList.add('new-class');
function Slidein(num) {
var elementWithTransformActiveClass = document.querySelector('.transform-active');
var element = document.getElementById(num);
if (!!elementWithTransformActiveClass) elementWithTransformActiveClass.classList.remove("transform-active");
if (element !== elementWithTransformActiveClass) {
element.classList.add("transform-active");
var buttonId = num.replace('div', 'button');
var button = document.getElementById(buttonId);
// and now you can add a new class to the button
button.classList.add('new-class');
}
}
要查看可以在所有HTML元素上使用的所有属性和方法,请访问:w3schools.com/jsref/dom_obj_all.asp