Javascript滑块按钮

时间:2019-03-07 05:51:33

标签: javascript slider

我正在使用Javascript图像滑块。我想了解以下代码,因为这里var i= image.length和相同的var i接受了for循环命令。我对它的工作方式感到困惑。

<script type="text/javascript">

    var slider_content = document.getElementById('box');

    var image = ['a','b', 'c', 'd','e'];

    var i = image.length;


    // function for next slide 

    function nextImage() {
        if (i<image.length) {
            i= i+1;
        } else {
            i = 1;
        }
        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
    }


    // function for prew slide

    function prewImage(){

        if (i<image.length+1 && i>1) {
            i= i-1;
        } else {
            i = image.length;
        }
        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";

    }

1 个答案:

答案 0 :(得分:1)

代码很简单,而且确实没有Ashkan所说的for循环。我将根据我的理解尝试解释代码。 在开始的地方

var i = image.length

,此代码获取Image的长度,对于您的情况,该长度始终为5。

调用下一个函数时,

function nextImage() {
  //When the next image function is called, the code first checks that the value i is not
  //equal or greater than image.length, since we cannot really increment i to be greater 
  //than the available images.

        if (i<image.length) {
  //Our current index is either 1, 2, 3, or 4 so we can set our current index to 5 and 
  //show image 5

            i= i+1;
        } else {
  //Our index is 5 so we have to set our index to 1. 
  //We cannot increment because we dont have image 6 or more

            i = 1;
        }
  //Show image at current index. Seems like your images are starting from Image 0 to 
  // image 4 so we subtract one.

        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
    }

调用上一个图像函数时,

function prewImage(){
  //When the previous image function is called, the code first checks that the value i is not
  //less than image.length and that our current index is greater than 1.

        if (i<image.length+1 && i>1) {
  //Our current index is equal or greater than 2 so we can set it to a value just below
  //it. Notice this can never be 1 since 1-1 = 0 which is not a valid index
            i= i-1;
        } else {
  //Current index is 1
  //If the current index is 1, set it to the length of the images which is also the index
  // of the last image, that is 5.
            i = image.length;
        }
  //Show image at current index. Seems like your images are starting from Image 0 to 
  // image 4 so we subtract one.
        slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";

    }

希望这会有所帮助,谢谢。