单击jQuery滑块

时间:2016-08-16 17:57:50

标签: jquery

我想在单击滑块时使此滑块执行此操作。我怎样才能做到这一点?这是代码:http://jsfiddle.net/EjZzs/15/

$(function() {

//settings for slider
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;

//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);

var interval;

function startSlider() {
    interval = setInterval(function() {
        $slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
            if (++currentSlide === $slides.length) {
                currentSlide = 1;
                $slideContainer.css('margin-left', 0);
            }
        });
    }, pause);
}
function pauseSlider() {
    clearInterval(interval);
}

$slideContainer
    .on('mouseenter', pauseSlider)
    .on('mouseleave', startSlider);

startSlider();

});

1 个答案:

答案 0 :(得分:1)

将执行滑动的代码移动到它自己的函数,并从setInterval和单击中调用它:

  function startSlider() {
    interval = setInterval(slide, pause);
  }

  function slide() {
    $slideContainer.animate({
      'margin-left': '-=' + width
    }, animationSpeed, function() {
      if (++currentSlide === $slides.length) {
        currentSlide = 1;
        $slideContainer.css('margin-left', 0);
      }
    });
  }

  $slideContainer
    .on('mouseenter', pauseSlider)
    .on('mouseleave', startSlider)
    .on('click', slide);

http://jsfiddle.net/uctr94ve/