Pause slide show on hover

2019-07-25 17:10发布

问题:

I have the following script to run a slideshow, that works just fine.

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


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


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
    }, 500, function () {
        $('#slider ul li:last-child').prependTo('#slider ul');
        $('#slider ul').css('left', '');
    });
};

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

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

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

But I want it to pause on mouse hover, and I've tried a few other suggestions I found here on SO (including the one below), but couldn't make any of them work with the code I have. Any ideas? Thanks.

$("#slider ul").mouseover(function() {
$("#slider ul").trigger('pause', true);
});

回答1:

You can use .stop(), clearInterval()

// define reference to `setInterval()` call
var interval = setInterval(function () {
    moveRight();
}, 5000);

// stop animations, clear `interval`
$("#slider ul").mouseover(function() {
  $(this).stop();
  clearInterval(interval);
});


回答2:

You can use clearInterval() to remove the interval.



回答3:

Hope this helps:

var timerObject=null; 

function StartSlide(){
timerObject = setInterval(function () {
    moveRight();
}, 5000);
}

function stopSlide(){
clearInterval(timerObject)
}

$("#slider ul").mouseover(function() {
stopSlide()
});

$("#slider ul").mouseleave(function() {
StartSlide()
});


回答4:

.stop() | jQuery API

JSfiddle Example: