JS realizes the effect of timed carousel

JS realizes the effect of timed carousel

Use super simple code to realize carousel

html part

<ul class="list">
            <li><img id="imgs" class="item" src="images/img1.JPG" alt=""></li>
        </ul>

As shown in the figure above, create a ul list, and bring a li to put the img image (why is it a li, the rest will be rendered in the js part using a loop, which is simple and fast).

js part

var index = 1;
function lb(){
    
    
    index++;
    if(index>4){
    
    
        index=1;
    }
    var img = document.getElementById("imgs");
    img.src = "images/"+index+".JPG";
}
setInterval(lb,2000)

define index

Variables to be used in carousel events;

define function

Define a lb() function, use the if statement to judge the value of the current index, and then execute

define img

Get the id of the picture, define a variable img to get the id of the element where the picture is located, and then use id.src to write the picture position of the current index (pictures should be named with Arabic numerals to facilitate the execution of the function; the format of the picture Be unified!)

The last step (implementing the carousel)

Use the setInterval function to implement timing, and you can call functions or calculate expressions according to the specified period (in milliseconds).

The above are the specific steps to realize the carousel map! It's the easiest way I think so far!

Guess you like

Origin blog.csdn.net/weixin_57037336/article/details/125278294