Javascript - 尝试使用JS将图像添加到幻灯片中,但它不起作用?

时间:2017-11-07 22:35:05

标签: javascript html image

嘿我试图制作一个用图像填充幻灯片的空容器的功能,每个图像都包含在它自己的div中。

我的网页有一定数量的模态图像,点击后会打开幻灯片图像相册。我得到这个工作1张图像,然后意识到,如果它有一定数量的不确定大小的幻灯片,我应该做一个填充幻灯片div的功能。我计划让每个模态图像的数据属性为" 1,2,3 ...等"并且有一堆数组,其中有多个对象,每个对象的名称相似,并且#34; 1,2,3 ......等等#34;然后我将使用此信息创建并将正确的div和图像附加到幻灯片放映容器中。我将发布我想要的幻灯片容器div看起来像我现有的代码,以及应该发生什么的小提琴。我是javascript的新手并感谢您的帮助。我不确定我在这里做错了什么,如果我还没有解释得那么好,那么我会添加更多。

编辑: 我注意到在我的模态图像中,如果在onClick中我首先放置fillSlides,其他两个函数不会工作(或者不会被调用),但是如果我把它放在最后它会打开一个空幻灯片。我不明白为什么。

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

当前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>

我希望我的.modal-content div在函数运行后看起来像:

<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:

&#13;
&#13;
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);
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

添加了一个动态生成幻灯片的功能。 HTML中没有幻灯片,箭头控件位于#content。你没有提供关于专辑如何存在的细节,所以我为2张额外的专辑制作了一个缩略图。此外,还有一个解决方案,解决您的问题,删除所有内容,箭头是例外。 CSS有点不稳定,但我确信你可以很容易地纠正它。

详情在演示

中发表

演示

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;