javascript - 将 CSS-Accordion 应用于不同的按钮

标签 javascript html css

我有这个代码:

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/

相关文章:

html - 带有大量 Logo 的 CSS Bootstrap 导航

jquery - HTML 元素的定位和滑动

html - 使用 CSS 将首字下沉创建为图像(具有辅助功能)

html - 有没有办法将CSS应用于数据属性?

html - 文本对齐不正确

javascript - 单击时淡出,除非单击输入元素

javascript - Php JSON 编码数组和解码中的意外标记错误

javascript - 在点击按钮上设置多个组件 - React

javascript - 如何在 nvd3 中对栏进行排序?

javascript - 将回调函数作为 html 数据属性传递