简体   繁体   English

图像元素在 src 更改时变为空? 幻灯片

[英]Image element becoming null on src change? Slideshow

Working on building a library, trying to put in a fading image slider, it shows the first image, but then when it tries to change I get TypeError: document.querySelector(...) is null.正在构建一个库,尝试放入一个褪色的图像滑块,它显示了第一个图像,但是当它尝试更改时,我得到 TypeError: document.querySelector(...) is null。 Any help would be great!任何帮助都会很棒!

 export let styl = (function() {
  let slideIndex = 0;
  return {

    simpleSlideShow: function() {
      //automatic Slider
      let i;
      let slides = document.getElementsByClassName("mySlides");
      console.log("Image change");
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      slideIndex++;
      if (slideIndex > slides.length) {
        slideIndex = 1;
      }
      slides[slideIndex - 1].style.display = "block";
    },
    slideShowImageSetup: function(timeDelay, id, images) {
      //Building HTML with given array of images
      let i;
      for (i = 0; i < images.length; i++) {
        let elem = document.createElement("img");
        elem.setAttribute("alt", "image");
        elem.setAttribute("src", images[i]);
        elem.setAttribute("class", "mySlides");
        document.querySelector(id).appendChild(elem);
      }
      setTimeout(styl.simpleSlideShow, 1);
      setInterval(styl.simpleSlideShow, timeDelay);
      return 1;
    },
    fadingSlideShow: function(id, images) {
      document.querySelector(id).className += "fadeOut";
      setTimeout(function() {
        document.querySelector(id).src = images[slideIndex];
        document.querySelector(id).className = "";
        slideIndex++;
        if (slideIndex == images.length) {
          slideIndex = 0;
        }
        setTimeout(styl.fadingSlideShow(id, images), 3000);
      }, 1000);
    },
  };
})();

Where I'm calling the function我在哪里调用函数

let images = [
  "https://cdn141.picsart.com/297231911148201.jpg?c256x256",
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSQIfOEjoaYJNDHGmdgRa8EQp50VCicpK0R_0QpZLftE2zzgJky"
];

styl.fadingSlideShow("#slider", images);
<img id="slider"></img>

css that makes the fade effect使淡入淡出效果的css

#slider {
    opacity: 1;
    transition: opacity 3s;
}

#slider.fadeOut {
    opacity: 0;
}

Your second setTimeout is not sending in the id or images to styl.fadingSlideShow.您的第二个 setTimeout 没有将 id 或图像发送到 styl.fadingSlideShow。

setTimeout(function(){styl.fadingSlideShow(id, images)}, 3000);

Also, put the second setTimeout inside the first one.另外,将第二个 setTimeout 放在第一个里面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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