如何控制自定义的javascript轮播

时间:2015-06-30 07:14:57

标签: javascript html twitter-bootstrap

我正在制作一个自定义的javascript轮播。我想为我的旋转木马制作控件。我正在寻找答案,但没有找到。

这是我正在使用的代码

 <div class="container">
  <div class="row">
    <div class="col-lg-6 top-space text-center float">
      <h3 class="heading">Image Slider</h3>
      <hr>
    </div>
    <div class="col-lg-6 float">
      <img src="img/slider1.jpg" class="img-responsive" id="mainImage">
    </div>
  </div>
</div>

javascript代码:

 var imagesArray = ["img/slider2.jpg","img/slider3.jpg","img/slider4.jpg"];
 var index = 0 ;

 function imageSlider(){

   var getImagePath = document.getElementById("mainImage");
   getImagePath.setAttribute("src",imagesArray[index]);
   index++;

   if(index >= imagesArray.length){
     index = 0;
   }
}

setInterval(imageSlider,4000);

这是图片:

enter image description here

2 个答案:

答案 0 :(得分:1)

以下是您的示例:

function imageSlider(){
  this.prev = function(){
    if(--this.index < 0) this.index = this.imagesArray.length - 1;
    this.start()
  };

  this.next = function(){
    if(++this.index >= this.imagesArray.length) this.index = 0;
    this.start()
  };

  this.start = function(){
    var getImagePath = document.getElementById("mainImage");
    getImagePath.setAttribute("src", this.imagesArray[this.index]);

    this.timeout && clearTimeout(this.timeout);
    this.timeout = setTimeout(this.next.bind(this),3000)	
  };
}

var myCarousel = new imageSlider();
myCarousel.imagesArray = ["http://i.stack.imgur.com/d5vO7.jpg?s=128&g=1", "http://i.stack.imgur.com/GNgxX.png?s=128&g=1","http://i.stack.imgur.com/kpQYd.png?s=128&g=1"];
myCarousel.index = 0;
myCarousel.start()
<div class="container">
  <div class="row">
    <div class="col-lg-6 float">
      <img src="img/slider1.jpg" class="img-responsive" id="mainImage">
      <p><button onclick="myCarousel.prev()">Prev</button>
      <button onclick="myCarousel.next()">Next</button></p>
    </div>
  </div>
</div>

答案 1 :(得分:0)

首先应该在分配新路径之前增加索引。之后,只需创建一个调用您创建的imageSlider()函数的按钮,滑块应向前移动图像。如果你不想让它倒退,你将不得不创造另一个功能来做到这一点。类似的东西:

   var getImagePath = document.getElementById("mainImage");
   index--;
   getImagePath.setAttribute("src",imagesArray[index]);


   if(index <= 0){
     index =  imagesArray.length - 1;
   }

要实现按钮功能,您可以使用jQuery .click()方法:https://api.jquery.com/click/

或使用仅限Javascript的替代方法:http://www.w3schools.com/jsref/event_onclick.asp