网络幻灯片是一系列图像或文本,在特定时间间隔内按顺序显示一个元素。

在这篇教程中,你可以按照以下简单步骤创建幻灯片:

写一些标记文档

  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Slideshow</title>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <div id="slideshow-example" data-component="slideshow">
        <div role="list">
          <div class="slide">
            <img src="" alt="">
          </div>
          <div class="slide">
            <img src="" alt="">
          </div>
          <div class="slide">
            <img src="" alt="">
          </div>
        </div>
      </div>
    <script src="slideshow.js"></script>
    </body>
  </html>

写样式来隐藏幻灯片,只显示一张幻灯片

要隐藏幻灯片,你必须为其提供默认样式。它将指明你仅显示一张处于活动状态或想要显示的幻灯片。

  [data-component="slideshow"] .slide {
    display: none;
  }

  [data-component="slideshow"] .slide.active {
    display: block;
  }

每隔一定时间更换显示幻灯片

更改显示哪些幻灯片的第一步是选择幻灯片包装,然后选择其幻灯片。

选择幻灯片时,你必须浏览每张幻灯片,并根据要显示的幻灯片添加或删除活动的 class。然后,只需在一定时间间隔内重复该过程即可。

请记住,从幻灯片删除活动 class 时,由于上一步中定义的样式,你是将其隐藏了。但是,当你给幻灯片添加活动 class 时,你将覆盖样式 display:nonedisplay:block,因此幻灯片将向用户显示。

  var slideshows = document.querySelectorAll('[data-component="slideshow"]');
  
  // Apply to all slideshows that you define with the markup wrote
  slideshows.forEach(initSlideShow);

  function initSlideShow(slideshow) {

    var slides = document.querySelectorAll(`#${slideshow.id} [role="list"] .slide`); // Get an array of slides

    var index = 0, time = 5000;
    slides[index].classList.add('active');  
    
    setInterval( () => {
      slides[index].classList.remove('active');
      
      //Go over each slide incrementing the index
      index++;
      
      // If you go over all slides, restart the index to show the first slide and start again
      if (index === slides.length) index = 0; 
      
      slides[index].classList.add('active');

    }, time);
  }

Codepen 查看代码示例

原文:How to Create a Slideshow with HTML, CSS, and JavaScript