0

我不知道为什么我的数组中的最后一个图像没有显示。有什么帮助吗?

const imageBox = document.querySelector('.image-box');
let startIndex = 0;
let endIndex   = imageArray.length - 1;
let timer      = 1000;

const slider = () => {
  imageBox.textContent = '';
  imageArray.forEach((img) => {
    if (startIndex <= endIndex) {
      let image = document.createElement('img');
      image.src = img;
      imageBox.append(image);
      startIndex++;
    } else {
      startIndex = 0;
    }
  })
  setTimeout("slider()", timer);
}

window.addEventListener('DOMContentLoaded', slider);
4

2 回答 2

0

尝试使用 appendChild 而不是 append:

    const imageBox = document.querySelector('.image-box');
    let startIndex = 0;
    let endIndex   = imageArray.length - 1;
    let timer  = 1000;

    const slider = () => {
       imageBox.textContent = '';
       imageArray.forEach((img) => {
       if (startIndex <= endIndex) {
       let image = document.createElement('img');
       image.src = img;
       imageBox.appendChild(image);
       startIndex++;
       } else {
         startIndex = 0;
      }
    })
      setTimeout("slider()", timer);
  }

   window.addEventListener('DOMContentLoaded', slider);
于 2021-01-15T04:17:17.470 回答
0

完整代码:
1:加载所有图像
2:加载所有图像时运行图像滑动

它仅显示加载正常的图像

let imgIndex = -1  // no image at start
  ;
const
    imageBox = document.querySelector('.image-box > img')
  , timer   = 2000
  , imageArray = 
    [ { path:'https://picsum.photos/id/237/200/300', status:'none', img:null }
    , { path:'https://picsum.photos/id/238/200/300', status:'none', img:null }
    , { path:'https://picsum.photos/id/239/200/300', status:'none', img:null }
    , { path:'https://picsum.photos/id/240/200/300', status:'none', img:null }
    ] 
  , loadImage = ref => new Promise( resolve =>
      {
      ref.img = new Image();
      ref.img.onload  =_=>{ ref.status='OK';  resolve() };
      ref.img.onerror =_=>{ ref.status='bad'; resolve() };
      ref.img.src = ref.path;
      })
  , nextImg = () =>
      {
      do 
        imgIndex = ++imgIndex % imageArray.length
      while 
        (imageArray[imgIndex].status != 'OK')
      imageBox.src = imageArray[imgIndex].path 
      }
  , slider = () =>
      {
      Promise
      .all(imageArray.map(el=>loadImage(el) )) // load all img
      .then(()=>
        {
        nextImg()
        setInterval(nextImg, timer);
        })
      }

window.addEventListener('DOMContentLoaded', slider);
.image-box img {
  border: 1px solid darkblue;
  padding: .6em;
  margin: 1em;
  }
<div class="image-box">
  <img src="">
</div>

于 2021-01-15T04:19:54.180 回答