I am currently trying to make an image gallery based on the code here: http://www.w3schools.com/howto/howto_css_modal_images.asp
This code works fine for a single image, however it doesn't work when you try and add more. I believe this has to do with the javascript using IDs, but when I try to use classes in place of IDs that code will not work.
Has anybody had any luck using this example from W3 Schools to create a working gallery?
Thanks! :)
Here's the HTML and javascript from the body of my code.
<div class="container" id="gallery">
<h1>Gallery</h1>
<!-- Trigger the Modal -->
<img id="thumbnail-01" class="myImg" src="images/thumbnail.jpg" alt="Trolltunga, Norway" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- The Close Button -->
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- Modal Content (The Image) -->
<img class="modal-content" id="modal-image">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
<!-- Trigger the Modal -->
<img id="thumbnail-02" class="myImg" src="images/thumbnail.jpg" alt="Trolltunga, Norway" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- The Close Button -->
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- Modal Content (The Image) -->
<img class="modal-content" id="modal-image">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
</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.getElementsByClassName('myImg');
var modalImg = document.getElementById("modal-image");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…