我是JavaScript新手,渴望了解更多信息。 我尝试用模态做一些事情,遇到了一个我似乎无法解决的难题。 我希望彼此相邻有四张图片,当我点击它时,它会显示一个模态。因此图A显示模态A,图B显示模态B等。我现在似乎只能让第一张照片工作,而其他照片甚至都没有显示模态。 有人可以帮我这个吗?提前谢谢
<div class = "StyleTextBox">
<h1>Present</h1>
<img id="myImg" src="C:/Users/s155310/Pictures/showcase pictures/guitar1.jpg" alt="guitar" width="200" height="auto">
<img id="myImg" src="C:/Users/s155310/Pictures/showcase pictures/1.jpg" alt="thing" width="200" height="auto">
//The Modal
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"> </div>
<p> Some text </p>
</div>
<script>
// 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.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
答案 0 :(得分:0)
具有多个具有相同ID的元素是无效的HTML。您应该更改图像元素,而不是使用类。在JavaScript中,您可以通过document.getElementsByClassName('classNameHere')
访问这些类,并通过循环迭代它们以设置onclick属性。例如:
<div class = "StyleTextBox">
<h1>Present</h1>
<img class="myImg" src="C:/Users/s155310/Pictures/showcase pictures/guitar1.jpg" alt="guitar" width="200" height="auto">
<img class="myImg" src="C:/Users/s155310/Pictures/showcase pictures/1.jpg" alt="thing" width="200" height="auto">
//The Modal
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"> </div>
<p> Some text </p>
</div>
<script>
// 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 images = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
function openModel(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
for(var img = 0; img < images.length; img++) {
images[img].onclick = openModel;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
答案 1 :(得分:0)
问题不在于使用唯一ID。而是使用类