2016-09-13 12 views
0

私のウェブページにはいくつかのモーダルを実装しています。私のコードは以下の通りです。複数のモーダルを閉じることができませんか?

HTML

<div id="modal" class="modal"> 
    <div class="modal-content"> 
    <span class="close">&times</span> 
    <h3>Title</h3> 
    </div> 

</div> 

はJavaScript

<script> 
    var modal = document.getElementById('modal'); 
    var btn = document.getElementById("mybtn"); 
    var span = document.getElementsByClassName("closeSel")[0]; 
    btn.onclick = function() { 
     modal.style.display = "block"; 
    } 
    span.onclick = function() { 
     modal.style.display = "none"; 
    } 
    window.onclick = function(event) { 
     if (event.target == modal) { 
      modal.style.display = "none"; 
     } 
    } 
    </script> 

すべての非常にシンプルな、私の問題は、私は別のモーダルを追加しようとしたとき、私は、id値を変更し、別のモーダルのために別のスクリプトを追加発生しますそれはうまく動作しますが、実際にモーダルを閉じることになると、それは動作しません。 同じクラスを使用している閉じるボタンのCSSについては、これが原因です。

/* The close Button */ 
.close { 
    color: #aaaaaa; 
    float: right; 
    font-style: arial; 
    font-size: 28px; 
    font-weight: bold; 
} 

.close:hover, 
.close:focus { 
    color: #000; 
    text-decoration: none; 
    cursor: pointer; 
} 
+0

'VARスパン= document.getElementsByClassName( "closeSel")[0]'ここでUはあなたが '<スパンクラス= "近い">&回' closeSel' 'としてではなく、HTMLコード内のクラス名を使用していますクラスcloseを使用して –

+0

ああ申し訳ありませんが、私は変数を編集したので、スタックオーバーフローの方が簡単です。それはちょうどタイプミスです – cmca

+0

jsfiddleを作成すると問題が再現できます。原因 –

答えて

0

私はそれがクラスだろう疑う彼らは一意である必要として、私はあなたにもボタンのIDを変更するか、のIDに沿ってより多くのを思うだろうか? クリックとクローズの機能がパラメータを取らない場合は、インラインonclick htmlを使用するだけで、IDが混乱することはありません。 コードでは、HTMLには表示されないクラス「closeSel」も参照しています

+0

私はクラスの代わりにidとして呼び出すと、違いがあるかどうかを確認します – cmca

0

閉じるが、各スパン要素を反復処理する必要があります。私は実際の例を付けました。

<!-- Test Modal --> 
    <div id="myModal" class="modal"> 
     <div class="modal-content"> 
     <span class="close">&times;</span> 
     <p>First Test text in modal..</p> 
     </div> 
    </div> 

    <!-- Test Modal 2 --> 
    <div id="myModal2" class="modal"> 
     <div class="modal-content"> 
     <span class="close">&times;</span> 
     <p>Second test text in modal..</p> 
     </div> 
    </div> 

<script> 

     var span = document.getElementsByClassName("close"); 
     var modal; 
     var btn = document.getElementsByClassName("button is-primary is-small modal-button"); 

     for (var i = 0; i < btn.length; i++) { 
     var thisBtn = btn[i]; 
     thisBtn.addEventListener("click", function(){ 
      modal = document.getElementById(this.dataset.modal); 
      modal.style.display = "block"; 
     }, false); 
     } 

     // iterate through each span element for each modal 
     for (var i = 0; i < span.length; i++){ 
     span[i].onclick = function(){ 
      modal.style.display = "none"; 
     } 
     } 

     // When the user clicks anywhere outside of the modal, close it 
     window.onclick = function(event) { 
      if (event.target == modal) { 
       modal.style.display = "none"; 
      } 
     } 
    </script> 
+0

このスクリプトをテストしましたか?または、共有するための実例がありますか? – matoneski

関連する問題