我有这个代码:
Javascript:
var acc = document.getElementsByClassName("button");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
CSS:
.button{
display:block;
height:431px;
width:100%;
font-family: Futura, 'Trebuchet MS', Arial, sans-serif;
color:black;
font-size:80px;
margin:0 auto;
background-color:transparent;
border-style:none;
}
.button:hover{
background: url('pcluj.jpg') ;
background-size: cover;
}
.button1{
display:block;
height:431px;
width:100%;
font-family: Futura, 'Trebuchet MS', Arial, sans-serif;
color:black;
font-size:80px;
margin:0 auto;
background-color:transparent;
border-style:none;
}
.button1:hover, .button1.active{
background: url('bucuresti.jpg') ;
background-size: cover;
}
.button2{
display:block;
height:431px;
width:100%;
font-family: Futura, 'Trebuchet MS', Arial, sans-serif;
color:black;
font-size:80px;
margin:0 auto;
background-color:transparent;
border-style:none;
}
.button2.active, .button2:hover{
background: url('sibiu.jpg') ;
background-size: cover;
transition: 0.6s ease-in-out;
}
div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: 0.6s ease-in-out;
opacity: 0;
}
HTML:
<center>
<button class="button" id="button">CLUJ</button>
</center>
<div class="panel">
<p>Lorem ipsum...</p>
</div>
<center>
<button class="button1" id="button1" >BUCURESTI</button>
</center>
<div class="panel" id='panel'>
<p>Lorem ipsum...</p>
</div>
<center>
<button class="button2" id="button2">SIBIU</button>
</center>
<div class="panel">
<p>Lorem ipsum...</p>
</div>
如何让所有按钮都像 Accordion 一样?我有不同的类名,因为当我将鼠标悬停在每个按钮上时,它有不同的背景图像。
此版本的代码不适用于所有按钮,仅适用于第一个按钮。该怎么办?
最佳答案
变量 acc 是类名为“button”的按钮数组。但是您的 html 代码中只有一个按钮元素的类名称为按钮,因此它适用于按钮 CLUZ。由于您已经为每个按钮定义了一个 id,请尝试在 css 中使用 id 选择器(#button、#button1、#button2)而不是类选择器(.button、.button1、.button2),这可以帮助您获得不同的背景图像。并为所有按钮使用相同的类名,并在下面的行中使用它
var acc = document.getElementsByClassName("buttonName");
关于javascript - 将 CSS-Accordion 应用于不同的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36898042/