我正在创建一个网站,用户可以点击图片打开包含菜单项的模态,而第一个模态工作正常,后续模态则没有。
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和模态框非常新,所以任何输入都会受到赞赏,谢谢。
答案 0 :(得分:0)
modal
中的modal.style.display = none
是指ID为“模态”的元素。你有两个元素,这个但是 id
给予HTML元素需要唯一。
这适用于所有id
,因此您必须更改为图片提供唯一ID。