2016-04-27 34 views
1

我有这样的代码:应用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> 

我怎样才能使所有的按钮都像一个手风琴?我有不同的类名,因为当我将它悬停时,每个按钮都有不同的背景图片。

此版本的代码不适用于所有按钮,仅适用于第一个按钮。什么是要做?

回答

0

变量acc是一个类名为“button”的按钮数组。但是你的类名只能作为你的html代码中的一个按钮元素的按钮,所以它适用于按钮CLUZ。正如你已经为每个按钮定义了一个id,请尝试在css中使用id选择器(#button,#button1,#button2),而不是类选择器(.button,.button1,.button2),它可以帮助你获得不同的背景图像。并且对于所有按钮都有相同的类名并在下面的行中使用它

var acc = document.getElementsByClassName("buttonName");