2016-04-27 18 views
1

異なるボタンに適用しますはCSS-アコーディオンは、私はこのコードを持っている

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は、クラス名「ボタン」を持つボタンの配列です。しかし、クラス名はHTMLコード内のボタン要素の1つのみのボタンになっているので、ボタンCLUZで機能します。それぞれのボタンのidを定義したので、クラスセレクタ(.button、.button1、.button2)ではなく、CSSでidセレクタ(#button、#button1、#button2)を使って、異なる背景画像を持つのに役立ちます。すべてのボタンに同じクラス名を付けて、下の行に使用してください。

var acc = document.getElementsByClassName("buttonName"); 
関連する問題