0
我創建了一個網站,用戶可以點擊圖像打開一個模式與菜單項,而第一模態工作正常,後來的模態不會。每頁有多個模態
JS代碼:
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myImg");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.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>
HTML,其中它的使用:
<div class="col-md-3">
<h2>Starters</h2>
<img src="http://foodnetwork.sndimg.com/content/dam/images/food/fullset/2007/2/9/0/ie0102_coleslaw.jpg" height="100%" width="100%" id="myImg">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<br>
<h2>Starters</h2>
</div>
<div class="modal-body">
<p><b>PRODUCT <span style="display:inline-block; width: 75%;"></span> PRICE</b></p>
<hr>
<p> Humus <span style="display:inline-block; width: 78%;"></span> £3.00</p>
<p> Dolma <span style="display:inline-block; width: 78%;"></span> £3.20</p>
<p> Coleslaw <span style="display:inline-block; width: 77%;"></span> £1.50</p>
<p> Prawn Cocktail <span style="display:inline-block; width: 73.5%;"></span> £4.60</p>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<h2>Wraps</h2>
<img src="http://harryskebabs.com/images/demo/menu-main/menu-item-large-20.jpg" height="100%" width="100%" id="myImg">
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<br>
<h2>Starters</h2>
</div>
<div class="modal-body">
<p><b>PRODUCT <span style="display:inline-block; width: 75%;"></span> PRICE</b></p>
<hr>
<p> Chicken Wrap <span style="display:inline-block; width: 78%;"></span> £3.00</p>
<p> Doner Wrap <span style="display:inline-block; width: 78%;"></span> £3.20</p>
<p> Shish Wrap <span style="display:inline-block; width: 77%;"></span> £1.50</p>
<p> Kofte Wrap <span style="display:inline-block; width: 73.5%;"></span> £4.60</p>
</div>
</div>
</div>
</div>
表示將如預期,而第二個將不會顯示在所有的第一個模式對話框,我寧可不要不必要地複製JavaScript,如果我不需要,這就是爲什麼我厭倦了這種方法。
非常新的JS和模態框,所以任何輸入將不勝感激,謝謝。
因此,修復只是將「modal.style.display = none」重命名爲「modal2.style.display = none」,然後進行更改以反映這一點? –
修正的回答。你需要做的是重命名你的ID,以便沒有重複。所以myModal0,myModal1和myImg0以及myImg1。然後,您可以修改事件句柄以根據名稱的數字後綴關閉/打開適當的模式。 – Pineda
我需要在JS中聲明一個新變量,所以mymodal1 = getelementbyid(「modal1」)等?然後重新相應我的js?因爲我剛剛嘗試過,現在模態會在圖像上工作,所以在這方面幫助很大。但現在該模式仍然會以「啓動器」內容而不是「包裝」內容打開。如果這會有所幫助,我可以提供該文件的pastebin。 –