-->

Trigger Alert When Slider Moves Left A Certain Amo

2019-09-21 07:53发布

问题:

So, I am going to actually kill two birds with one stone. First off, I am trying to trigger an alert once the slider moves left to a specific degree. For example, once it goes to, let’s say, the 3rd slide I would like for it to trigger an alert. Also, I need help with the cycling of the slider. I want the slider to cycle like a rotation (360), but instead at the end of the cycle it slides all the way back to the start. View the Codepen to have a better understanding of what I mean. Thank you for your time. Your help is much appreciated.

Live Codepen

var W = $('#image_rotator').width(),
N = $('#slider .slide').length,
C = 0,
intv;

if (N <= 1) $('#left, #right').hide();
$('#slider').width(W * N);

$('#left, #right').click(function() {
C = (this.id == 'right' ? ++C : --C) < 0 ? N - 1 : C % N;
$('#slider').stop().animate({
left: -C * W
}, 300);
});

function setResetInterval(e) {

var intv = $("#slider");
if (e) {
timer = setInterval(function() {
$('#right').click();
}, 1000);
} else {
clearInterval(timer);
}

$('#slider').click(function() {
var x = $('#slider').offset();
alert("Top: " + x.top + " Left: " + x.left);
});
}

$("#btn").click(function(e) {
e.preventDefault();
setResetInterval(true);
});
$("#btn2").click(function(e) {
e.preventDefault();
setResetInterval(false);
});
$('#slider').hover(function(e) {
return e.type == 'mouseenter' ? setResetInterval(false) : setResetInterval(true);
});

回答1:

This accomplishes both of the things that you wanted using the optional callback parameter in the animate function. It checks first to see if the variable C (the 0-based index of the current slide) is equal to 2 (3 in 1-based indexing), and shows an alert if it is. Then it checks to see if C is equal to 10 (which would mean that the slide currently being shown is the 9th one; The 9th image is just a duplicate of the 1st one) If it is on the 9th one, then jump back to the first one and trigger $("#right").click();.

$('#left, #right').click(function() {
    C = (this.id == 'right' ? ++C : --C) < 0 ? N - 1 : C % N;
    $('#slider').stop().animate({
        left: -C * W
    }, 300, function() {
        if (C == 2){alert("3rd");}
        if (C == 10) {
            $('#slider').css("left", "0");
            $('#right').click();
        }
    });
});

JSFiddle (Because CodePen's layout is weird to me)