我已经完成了此滑块,但没有自动滑动,应该添加什么代码来使该自动滑动?我应该将该代码放在哪里?

我尝试将setinterval用作goNext函数,但仍无法正常工作

class Slider {
    constructor(props) {
        this.rootElement = props.element;
        this.slides = Array.from(
            this.rootElement.querySelectorAll(".slider-list__item")
        );
        this.slidesLength = this.slides.length;
        this.current = 0;
        this.isAnimating = false;
        this.direction = 1; // -1

        this.navBar = this.rootElement.querySelector(".slider__nav-bar");
        this.thumbs = Array.from(this.rootElement.querySelectorAll(".nav-control"));
        this.prevButton = this.rootElement.querySelector(".slider__arrow_prev");
        this.nextButton = this.rootElement.querySelector(".slider__arrow_next");

        this.slides[this.current].classList.add("slider-list__item_active");
        this.thumbs[this.current].classList.add("nav-control_active");

        this._bindEvents();
    }

    goTo(index, dir) {
        if (this.isAnimating) return;
        var self = this;
        let prevSlide = this.slides[this.current];
        let nextSlide = this.slides[index];

         self.isAnimating = true;
         self.current = index;
         nextSlide.classList.add("slider-list__item_active");

         goStep(dir) {
             let index = this.current + dir;
             let len = this.slidesLength;
             let currentIndex = (index + len) % len;
             this.goTo(currentIndex, dir);
         }

         goNext() {
             this.goStep(1);
         }

         goPrev() {
             this.goStep(-1);
         }

         _navClickHandler(e) {
             var self = this;
             if (self.isAnimating) return;
             let target = e.target.closest(".nav-control");
             if (!target) return;
             let index = self.thumbs.indexOf(target);
             if (index === self.current) return;
             let direction = index > self.current ? 1 : -1;
             self.goTo(index, direction);
         }

         _bindEvents() {
             var self = this;
             ["goNext", "goPrev", "_navClickHandler"].forEach(method => {
                  self[method] = self[method].bind(self);
             });
             self.nextButton.addEventListener("click", self.goNext);
             self.prevButton.addEventListener("click", self.goPrev);
             self.navBar.addEventListener("click", self._navClickHandler);
         }
    }

    // ===== init ======
    let slider = new Slider({
        element: document.querySelector(".slider")
    });


因此,如果有人能告诉我如何使该旋转木马滑块自动滑动,我将非常感谢。

最佳答案

只需调用下一个函数

setInterval(function()
{
slider.goNext();
}, 1000);

10-05 21:54