Bootstrap模态图像不起作用 - 多个

时间:2016-10-03 15:04:28

标签: boo

我只是按照w3school教程获取了这个bootstrap模态图像。我的页面中有两张图像卡。所以我需要弹出那两张图片。但它只使用一个图像。

Link to w3school article

 <!-- Trigger the Modal -->

<img id="myImg" src="http://d14dsi4x2zx6ql.cloudfront.net/files/styles/welcome_image/public/VCW_TI_5_BayLoop_Hero_Manley_1280x642_sized.jpg?itok=EaARDZt8" alt="">

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- The Close Button -->
  <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span>

  <!-- Modal Content (The Image) -->
  <img class="modal-content" id="img01">

  <!-- Modal Caption (Image Text) -->
  <div id="caption"></div>
</div>

我插入&#34; myImg&#34;我的另一张照片中有id,但它没有用。第一个图像弹出窗口按预期工作。这里会缺少什么?

2 个答案:

答案 0 :(得分:1)

ID必须是唯一的,请参阅此处的示例。 https://fiddle.jshell.net/wg5p60g7/

答案 1 :(得分:1)

您无法为两个元素提供相同的ID 如果你想为两者做同样的动作,你可以给他们上课

<img class="myImg" src="http://placehold.it/850x450" alt="image1" width="200">
<img class="myImg" src="http://placehold.it/700x400/f00" alt="image2" width="200">

和js将是:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
//iterate over img to add click event for each one,, jquery will make it much easier
for(var i=0;i< img.length;i++){
  img[i].onclick = function(){
      modal.style.display = "block";
      modalImg.src = this.src;
      captionText.innerHTML = this.alt;
  }
}

//jquery option
/*$('.myImg').on('click', function(){
    modal.style.display = "block";
  modalImg.src = $(this).attr('src');
  captionText.innerHTML = $(this).attr('alt');
})*/

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

Demo