轮播图自动播放 定时器使用

轮播图自动播放 定时器使用

DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
  <style>
    ul,
    li {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      width: 500px;
      height: 300px;
      border: 1px solid black;
      position: relative;
    }

    li {
      width: 500px;
      height: 300px;
      position: absolute;
      display: none;
    }

    img {
      width: 100%;
      height: 100%;
    }
  style>
head>

<body>

  <ul id="list">
    <li style="display:block"><img src="./images/1.jpg" alt="">li>
    <li><img src="./images/2.jpg" alt="">li>
    <li><img src="./images/3.jpg" alt="">li>
  ul>


  <script>

    var liList = document.getElementsByTagName('li')

    // 定义一个变量表示当前要显示和图片下标,初始为0
    var index = 0

    // 定义一个全局变量
    var intervalId

    // 初始化执行
    run()
    function run() {
      intervalId = setInterval(function () {
        index++

        // 先隐藏所有的图片
        for (var i = 0; i < liList.length; i++) {
          liList[i].style.display = 'none'
        }

        // 当下标大于2的时候,则index还原为0
        // if (index > 2) {
        //   index = 0
        // }

        // 还可以这样写
        index = index % 3

        // 显示当前下标的图片
        liList[index].style.display = 'block'
      }, 1000)
    }


    list.onmouseover = function () {
      // 清除定时器
      clearInterval(intervalId)
    }

    list.onmouseout = function () {
      // 移出再加上定时器
      run()
    }



  script>

body>

html>

你可能感兴趣的:(html,css,js,jq,javascript,html,前端)