js small case-carousel diagram (timer)

Do you have any way to realize the carousel?
Today I’m going to introduce a method
to implement with JS

1. Find a few pictures you like
2. Create a new HTML page
3. First add a picture in the body

Set the id value of the picture to img1, students can set it freely, and the width and height can be set according to their own preferences

<img id="img1" src="../img/banner_1.jpg" height="400" width="1500"/>
4. Create a script tag below the body

Here because we want to make a carousel picture, we use a cycle timer to
define a cycle timer: switch one picture every 2s, a total of four pictures, write a function in the cycle timer called changeImg(), define a variablei Used to accept the picture, assign the path of the picture to the src value of the picture, every time the picture changes, we let i Self-increasing when i Since increasing to 4, let i It is equal to 1, so that it can keep changing continuously to achieve the effect of carousel.

//图片每2秒变化一次,一共四张图片
setInterval(changeImg,2000)
    let i=1
    function changeImg(){
    
    
        if(i==4){
    
    
            i=1
        }
        img1.src='../img/banner_'+i+'.jpg'
        i++
    }

js little knowledge定时器

js timer is divided into two types

. Disposable timer : two ways

  • Start a one-time timer: setTimeout()
  • Clear one-time timer: clearTimeout()

Loop timer : two methods

  • Start the loop timer: setInterval()
  • Clear cycle timer: clearInterval()

Such a simple case of the emperor choosing a concubine is written~~~ The complete code is attached below~~~
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>轮播图</title>
</head>
<body>
<img id="img1" src="../img/banner_1.jpg" height="400" width="1500"/>
</body>
<script>
    //1.定义一个循环定时器:每2s切换一张图片
    setInterval(changeImg,2000)
    let i=1
    function changeImg(){
     
     
        if(i==4){
     
     
            i=1
        }
        img1.src='../img/banner_'+i+'.jpg'
        i++
    }
</script>
</html>

Click a thumbs up and leave, guest officer!

Guess you like

Origin blog.csdn.net/lcszz0302/article/details/110681421