自动和手动滑动图像

时间:2017-08-14 09:16:50

标签: javascript jquery html css

对于图像滑块我使用此代码

var sliderIndex = 0;

function initializeImageSlider() {
    var sliderImages = $(".sliderImg");

    for (var i = 0; i < sliderImages.length; i++) {
        sliderImages[i].style.display = "none";
    }
    sliderIndex++;
    if (sliderIndex > sliderImages.length) {
        sliderIndex = 1;
    }
    sliderImages[sliderIndex-1].style.display = "block";
    setTimeout(initializeImageSlider, 5000);
}

function changeSliderImage(direction) {
    sliderIndex += direction;
    alert("move " + direction);
}
#containerImageSlider {
    width: 200px;
    height: 200px;
}

.sliderImg{
    width: 100%;
    height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initializeImageSlider()">

<button onclick="changeSliderImage(-1)">-</button>
<div id="containerImageSlider">
    <img class="sliderImg" src="Resources/sliderImg1.png">
    <img class="sliderImg" src="Resources/sliderImg2.png">
    <img class="sliderImg" src="Resources/sliderImg3.png">
    <img class="sliderImg" src="Resources/sliderImg4.png">
    <img class="sliderImg" src="Resources/sliderImg5.png">
</div>
<button onclick="changeSliderImage(1)">+</button>

</body>

因此自动滑块工作正常。现在我添加了两个按钮,它们调用函数changeSliderImage(direction),在其中传递一个向前或向后移动的值。

如您所见,目前我只使用initializeImageSlider()功能来设置自动滑块。

如何创建一个功能,让这个自动和手动过程有效?

我不知道如何拆分我的initializeImageSlider()函数。

1 个答案:

答案 0 :(得分:1)

您可以创建仅更新滑块的函数updateImageSlider(),无论sliderIndex是增加还是减少。然后,每次倒计时达到5秒或用户点击按钮时,您只需调用此方法。

此代码应该按您的要求执行:

var sliderIndex = 0;

function updateImageSlider() {
    var sliderImages = $(".sliderImg");

    for (var i = 0; i < sliderImages.length; i++) {
        sliderImages[i].style.display = "none";
    }
    if (sliderIndex > sliderImages.length) {
        sliderIndex = 1;
    }
    else if (sliderIndex < 1) {
        sliderIndex = sliderImages.length;
    }
    sliderImages[sliderIndex-1].style.display = "block";
}

var autoSlideHandler; // To reset the timer
function incrementImageSlider() {
    sliderIndex++;
    updateImageSlider();
    autoSlideHandler = setTimeout(incrementImageSlider, 5000);
}

function changeSliderImage(direction) {
    // Move the slider
    sliderIndex += direction;
    updateImageSlider();
    alert("move " + direction);
    // Reset the timer
    clearTimeout(autoSlideHandler);
    autoSlideHandler = setTimeout(incrementImageSlider, 5000);
}

$(incrementImageSlider); // Initialize the slider, function called on page load