简体   繁体   中英

Javascript - Trying to Add images to slideshow with JS but it doesn't work?

Hey I'm trying to make a function that fills an empty container of a slideshow with images, with each image being contained in it's own div.

My webpage have an undetermined amount of modal images which , when clicked, open a slideshow album of images. I got this working for 1 image then realized that to have it work for an undetermined amount of slideshows of undetermined size I should make a function that fills the slideshow div. I planned to have each modal image to have a data attribute of "1,2,3...etc" and have a bunch an array with multiple objects each named similarly "1,2,3...etc" then I'd use this information to create and append the correct divs and images to the slideshow container. I will post what I want the slideshow container div to look like, my existing code, and a fiddle of what is supposed to happen. I am new to javascript and appreciate the help. I'm not certain what I've done incorrectly here, and If I haven't explained well enough then I will add more.

Edit: I have noticed that in my modal image, if in the onClick I put fillSlides first, the other two functions won't work (or won't be called), but if I put it at the end it opens an empty slideshow. I don't get why.

https://jsfiddle.net/nhk3o0m1/26/

Current HTML:

<body >
 <h2 id="title" style="text-align:center">hellkkko</h2>

 <div class="row">
  <div class="column">
    <img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="openModal();currentSlide(1); fillSlides(this);" class="hover-shadow cursor">
  </div>
</div>

<div id="myModal" class="modal">
  <span class="close cursor" onclick="closeModal()">&times;</span>
  <div class="modal-content">

    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
  </div>
</div>

What I want my .modal-content div to look like after the function runs:

<div class="modal-content">

    <div class="mySlides">

      <img src="Images/LS_01.jpg" class="img">
    </div>

    <div class="mySlides">

      <img src="Images/LS_02.jpg" class="img">
    </div>

    <div class="mySlides">

      <img src="Images/LS_03.jpg" class="img">
    </div>

    <div class="mySlides">

      <img src="Images/LS_04.jpg" class="img">
    </div>

    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
  </div>

Javascript:

 function fillSlides(modalID) { var container = document.getElementsByClassName("modal-content"); var slides = { "1": ["Images/LS_01.jpg", "Images/LS_02.jpg", "Images/LS_03.jpg", "Images/LS_04.jpg"], "2": ["Images/LS_05.jpg", "Images/LS_06.jpg", "Images/LS_07.jpg", "Images/LS_08.jpg"], "3": ["Images/LS_09.jpg", "Images/LS_10.jpg", "Images/LS_11.jpg", "Images/LS_12.jpg"] }; var modal_num = modalID.getAttribute('data-modal'); for (var i = slides[modal_num].length; i > 0; i--) { var the_divs = document.createElement('div'); var s_img = document.createElement('img'); the_divs.className = 'mySlides'; s_img.src = slides[modal_num][i]; the_divs.appendChild(s_img); container.appendChild(the_divs); } } 
 <h2 id="title" style="text-align:center">hellkkko</h2> <div class="row"> <div class="column"> <img id="modal-1" src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" data-modal="1" onclick="openModal();currentSlide(1); fillSlides(this);" class="hover-shadow cursor"> </div> </div> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> </div> </div> 

Added a function that generates slides on the fly. There are no slides in HTML and arrow controls are in #content . You gave no details on how album exists so I made a thumbnail for 2 extra albums. Also, there's a solution to your problem concerning the removal of everything with the arrows being the exception. The CSS is a little wonky but I'm sure you can rectify it easily enough.

Details commented in demo

Demo

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no"> <title></title> <style> html, body { height: 100%; width: 100% } body { font-family: Verdana, sans-serif; margin: 0; } * { box-sizing: border-box; } .img { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; } .row { display:flex; justify-content:space-between; } .column { width: 25%; padding: 0 8px; } /* The Modal (background) */ .modal { display: none; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow-x: hidden; overflow-y: scroll; background: rgba(0, 0, 0, 0.9); } /* Modal Content */ .modal-content { position: relative; background-color: rgba(0, 0, 0, 0.9); margin: auto; padding: 0; width: 100%; max-width: 1200px; } /* The Close Button */ .close { color: white; position: absolute; top: 10px; right: 25px; font-size: 35px; font-weight: bold; } .close:hover, .close:focus { color: #999; text-decoration: none; cursor: pointer; } /* Next & previous buttons */ .prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; padding: 16px; margin-top: -50px; color: white; font-weight: bold; font-size: 20px; transition: 0.6s ease; border-radius: 0 3px 3px 0; user-select: none; -webkit-user-select: none; } /* Position the "next button" to the right */ .next { right: 0; border-radius: 3px 0 0 3px; } /* On hover, add a black background color with a little bit see-through */ .prev:hover, .next:hover { background-color: rgba(0, 0, 0, 0.8); text-decoration: none; } /* Number text (1/3 etc) */ .nth { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; right: 0; } img { margin-bottom: -4px; cursor: pointer } img.hover-shadow { transition: all .2s ease-in-out; } .hover-shadow:hover { transform: scale(1.1); } .modal-content { -webkit-animation-name: zoom; -webkit-animation-duration: 0.6s; animation-name: zoom; animation-duration: 0.6s; } @-webkit-keyframes zoom { from { -webkit-transform: scale(0) } to { -webkit-transform: scale(1) } } @keyframes zoom { from { transform: scale(0) } to { transform: scale(1) } } .slide img { display: block; height: 100%; margin: 0 auto; margin-bottom: 50px; } .slide { text-align: center; height: 80vh; display: none; } .cap { font-size: 1.5em; background: rgba(0, 0, 0, .4); position: absolute; z-index: 2; left: 0; top: 0; right: 0; text-align: center; color: #fff } .act { display: block } </style> </head> <body> <header> <div class="row"> <div class="column"> <img src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" onclick="album(img0, cap0);openModal();" class="hover-shadow"> </div> <div class="column"> <img src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" onclick="album(img1, cap1);openModal();" class="hover-shadow"> </div> <div class="column"> <img src="https://www.yosemitehikes.com/images/wallpaper/yosemitehikes.com-bridalveil-winter-1200x800.jpg" style="max-width:100%" onclick="album(img2, cap2);openModal();" class="hover-shadow"> </div> </div> </header> <section id="box"> <div id="xModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content" id='content'> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> </div> </div> </section> <footer> </footer> <script> /* 3 arrays are required: |= 1. An array of strings. || Each represents a src of an image |= 2. An array of strings. Each represents the || text of a figcaption |= 3. An empty array || For each additional album add #1 and #2, #3 || is emptied and reused at the beginning of || a new cycle. */ // Album 0 var img0 = [ "http://www.catholicevangelism.org/wp-content/uploads/2013/06/1200x800.gif", "http://chasingseals.com/wp-content/uploads/2014/02/greenlandBanner2000x800.jpg", "http://www.a1carpet-to.com/wp-content/uploads/2015/08/600x400.png", "https://support.kickofflabs.com/wp-content/uploads/2016/06/800x1200.png" ]; var cap0 = ['caption1', 'caption2', 'caption3', 'caption4']; // Album 1 var img1 = [ 'https://d3i6fh83elv35t.cloudfront.net/newshour/app/uploads/2016/05/729665main_A-BlackHoleArt-pia16695_full-1024x576.jpg', 'http://cdn.newsapi.com.au/image/v1/85fb305132eb20ebbb01af386983c8a1', 'http://science.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/Science/Images/Content/neptune-pia01492-ga.jpg', 'https://cdn.spacetelescope.org/archives/images/wallpaper1/heic1509a.jpg', 'https://i.giphy.com/media/JCUyexH8Zaf8k/giphy.webp' ]; var cap1 = ['Title I', 'Title II', 'Title III', 'Title IV', 'Title V' ]; // Album 2 var img2 = [ 'https://i.ytimg.com/vi/YeQnLnRvZ9Y/maxresdefault.jpg', 'https://www.thesun.co.uk/wp-content/uploads/2017/08/nintchdbpict000319076839.jpg?strip=all&w=960', 'https://i0.wp.com/www.sketchysloth.com/wp-content/uploads/2016/07/Legendary-Hanging-Garden-Of-Babylon.jpg?fit=710%2C495&ssl=1', 'https://i.ytimg.com/vi/YoRvJcgSDE4/maxresdefault.jpg', 'https://www.realmofhistory.com/wp-content/uploads/2017/01/mausoleum-at-halicarnassus-restored_1.jpg', 'http://www.ancient-origins.net/sites/default/files/field/image/statue-of-Zeus-Olympia.jpg', 'https://i.ytimg.com/vi/F2yYkbinGnc/maxresdefault.jpg' ]; var cap2 = ['Colossus of Rhodes', 'Great Pyramid of Giza', 'Hanging Gardens of Babylon', 'Lighthouse of Alexandria', 'Mausoleum at Halicarnassus', 'Statue of Zeus at Olympia', 'Temple of Artemis at Ephesus' ]; // Declare a empty array var data = []; // Declare some counters outside of loop (or inside of loop using let) var i, b, x; // Reference the node that will contain the slides var con = document.getElementById('content'); /* On each iteration... |= Empty the data array |= Create an object... || add a value from img[] to the src property || add a value from cap[] to the cap property || add the current value of index +1 to pos property || push the object into data array */ // Get the total length of data array // Call genSlides() function album(img, cap) { data.length = 0; for (i = 0; i < img.length; i++) { var ele = new Object; ele.src = img[i]; ele.cap = cap[i]; ele.pos = i + 1; data.push(ele); } var qty = data.length; genSlides(qty) } console.log(data); /* Pass qty through... |= On each iteration... |= Create a documentFragment || it will allow us to append new elements to || it while still not in the DOM || which is faster because tasks within the DOM || are slow for the browser in comparison. |= Notice that the data array is being used || to assign unique values. */ function genSlides(qty) { for (b = 0; b < qty; b++) { var frag = document.createDocumentFragment(); var slide = document.createElement('figure'); slide.id = 's' + b; slide.className = 'slide'; var cap = document.createElement('figcaption'); cap.className = 'cap'; cap.textContent = data[b].cap; var img = document.createElement('img'); img.classsName = 'img'; img.src = data[b].src; var nth = document.createElement('b'); nth.className = 'nth'; nth.textContent = data[b].pos + '/' + data.length; slide.appendChild(cap); cap.appendChild(nth); slide.appendChild(img); frag.appendChild(slide); con.appendChild(frag); } return false; } /* To avoid redundancy call sub functions within an initiating function || currentSlide() should start at 0, remember that all indexes by || default start at 0 and that the last index is .length - 1 || showSlides() has ben corrected. */ function openModal() { document.getElementById('xModal').style.display = "block"; showSlides(slideIndex); currentSlide(0); } /* To remove what's in #content with the exception of the arrows we || gather all .slides in a NodeList and use a loop to remove them. */ function closeModal() { document.getElementById('xModal').style.display = "none"; var slides = document.querySelectorAll(".slide"); for (x = 0; x < slides.length; x++) { con.removeChild(slides[x]); } } var slideIndex = 0; function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.querySelectorAll(".slide"); if (n > slides.length - 1) { slideIndex = 0 } if (n < 0) { slideIndex = slides.length - 1 } // Flipping a class is much cleaner than relying on style for (i = 0; i < slides.length; i++) { slides[i].classList.remove('act'); } slides[slideIndex].classList.add('act'); } </script> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM