Slick Slider binding hover event

2019-04-11 10:04发布

问题:

I am using the slick slider to display images. At the moment i have it so you can click on the navigation and it changes the main image display.

I am trying to get it to set the currently selected navigation on a hover event or mouseover event.

This is my current code for the navigation and display:

$('.slider-for').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
fade: true,
autoplay: true,
//trigger after the slide appears
// i is current slide index
afterChange: function (slickSlider, i) {
    //remove all active class
    $('.slider-nav .slick-slide').removeClass('slick-active');
    //set active class for current slide
    $('.slider-nav .slick-slide').eq(i).addClass('slick-active');
}
});


$('.slider-nav .slick-slide').eq(0).addClass('slick-active');

$('.slider-nav').slick({
    slidesToShow: 4,
    slidesToScroll: 1,
    asNavFor: '.slider-for',
    autoplay: true,
    dots: true,
    centerMode: true,
    focusOnSelect: true,
    vertical: true
});

and this is my fiddle

Is it possible to bind a mouseover event to slick?

回答1:

Should be possible. Never used slick before but on the first view it looks like a hover function is not implemented. I've created a fast basic approach how you could solve this with slick provided methods. See the fiddle. You should optimize getting the slick object, it's just a starting point for you. Also you should break the autoplay when hovering and restart it, just try around with the slick given methods.

$('.slider-nav').on('mouseenter', '.slick-slide', function (e) {
var $currTarget = $(e.currentTarget), 
    index = $currTarget.data('slick-index'),
    slickObj = $('.slider-for').slick('getSlick');

slickObj.slickGoTo(index);

});

Working fiddle



回答2:

Using the above answer as a base, I was able to come up with this solution. This fixes the issue when quickly mousing over from navslide #1 to #3, and having the slider-for hangup on slide #2.

var slideTimer;
    $('.slider-nav').on('mouseenter', '.slick-slide', function (e) {
        var $currTarget = $(e.currentTarget);
        $('.slider-nav .slick-slide').removeClass('slick-current');
        $currTarget.addClass('slick-current');

        slideTimer = setTimeout(function () {
            var index = $('.slider-nav').find('.slick-current').data('slick-index');
            var slickObj = $('.slider-for').slick('getSlick');
            slickObj.slickGoTo(index);
        }, 500);
    }).on('mouseleave', '.slick-slide', function (e) {
        clearTimeout(slideTimer);
    });