重置图像的间隔

Resetting Interval on an image

我有一个简单的图像滑块,是我从 Internet 上获得的。 JQuery 我知道的不多,只是我通过阅读我的代码所了解的。该代码有一个图像滑块,每 8 秒前进一次,并且有两个按钮可以在单击时向前或向后移动图像。我的问题是,当我单击按钮前进时,8 秒计时器不会重置,因此如果我在间隔中单击 6 秒,图像会在 2 秒后转到第三张图像。附件是我的 JQuery 代码。我尝试将 setInterval 添加到 moveLeft()moveRight() 函数,但它无法正常工作。很抱歉我缺乏 JQuery 知识,我在学校学习了基础 JavaScript 并且从那以后就没有使用过它。附件是我目前拥有的代码。

jQuery(document).ready(function ($) {


    setInterval(function () {
        moveRight();
    }, 8000);

    var slideCount = $('#slider ul li').length;
    var slideWidth = $('#slider ul li').width();
    var slideHeight = $('#slider ul li').height();
    var sliderUlWidth = slideCount * slideWidth;

    $('#slider').css({ width: slideWidth, height: slideHeight });

    $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

    $('#slider ul li:last-child').prependTo('#slider ul');

    function moveLeft() {
        $('#slider ul').animate({
            left: + slideWidth
        }, 1000, function () {
            $('#slider ul li:last-child').prependTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    function moveRight() {
        $('#slider ul').animate({
            left: - slideWidth
        }, 1000, function () {
            $('#slider ul li:first-child').appendTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    $('a.control_prev').click(function () {
        moveLeft();

        setInterval(function () {
        moveRight();
    }, 8000);

    });

    $('a.control_next').click(function () {
        moveRight();

        setInterval(function () {
        moveRight();
    }, 8000);

    });
});

您遇到这个问题是因为每当您创建一个新的向右移动的间隔时,您之前的间隔仍然存在。我建议你通过一个专门的函数来取消和重新初始化来确保你只有一个间隔:

var slideInterval = setInterval(function() {
  moveRight();
}, 8000);

function resetInterval() {
  clearInterval(slideInterval);
  slideInterval = setInterval(function() {
    moveRight();
  }, 8000);
}

然后,只需在点击时调用此函数:

$('a.control_prev').click(function() {
  moveLeft();
  resetInterval();
});

$('a.control_next').click(function() {
  moveRight();
  resetInterval();
});