首页 > 解决方案 > 如何为自动幻灯片编写循环?

问题描述

我想在幻灯片中添加一个循环,但我是 jQuery 新手,不知道该怎么做。这是代码:

$(function(){
    $("#slide_container").mouseout(function(){

        /*a loop here that change the images automatically when the mouse is not inside the div,
        get the index of the image and add to it like a for loop (i = 0; i < slides.length; i++) 
        but I still don't know which var should I add and how mouseout works.*/

    });

    $("#slide_container").mouseover(function(){
        $('#nextBtn').on('click', function(){
            console.log('clicked');
            var currentImg = $(".active");
            var nextImg = currentImg.next();

            if(nextImg.length){
                currentImg.removeClass('active').css('z-index', -10);
                nextImg.addClass('active').css('z-index', 10);
            }

        });

        $('#prevBtn').on('click', function(){
            console.log('clicked');
            var currentImg = $(".active");
            var prevImg = currentImg.prev();
            if(prevImg.length){
                currentImg.removeClass('active').css('z-index', -10);
                prevImg.addClass('active').css('z-index', 10);
            }

        })

标签: jquery

解决方案


你可以使用setInterval. 如果代码在惯性间隔内连续执行一段

您可以触发单击按钮以转发幻灯片

let s_interval = null;
const DELAY = 1000 //1s between each transition

$("#slide_container").mouseout(function(){
   const next_button = $('#nextBtn')
   s_interval = setInterval(()=> next_button.click(),DELAY)
});

$("#slide_container").mouseenter(function(){
   clearInterval(s_interval)
});

推荐阅读