Slick carousel sync to select

时光毁灭记忆、已成空白 提交于 2019-12-11 07:12:16

问题


I'm trying to sync a slick slider to an HTML select and having quite a hard time with it.

Here is my code :

$(function() {    
    $('.slick-slider').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        infinite: false,
        autoplay: false,
        draggable: false,
        arrows: false,
        swipe: false,
        speed: 200,
        fade: true,
        lazyLoad: 'progressive',
        cssEase: 'linear'
    });
    var select = $("#select");
    var $carousel = $('.slick-slider');
    $("#select").change(function() {
        goTo = select.selectedIndex;
        $carousel.slick("goTo", goTo);
    });
});

There is the same amount of options/slides.

I've been trying different things but since I'm quite ignorant JavaScript wise, I'm still stuck..

https://jsfiddle.net/70he30n1/

->>> Solution : https://jsfiddle.net/gpuubf5y/7/


回答1:


You can try this :

$( function() {

  var $carousel = $('.slick-slider').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    infinite: false,
    autoplay: false,
    draggable: true,
    arrows: false,
    swipe: true,
    speed:200,
    fade: true,
    lazyLoad: 'progressive',
    cssEase: 'linear'
  });
  var select = $("#select");
  $("#select").change( function() {      
    goTo = select.val();
    console.log( goTo );
    $carousel.slick( "goTo", goTo-1 );
  });
});

Working demo : https://jsfiddle.net/gpuubf5y/




回答2:


You don't need to access native properties via jQuery. If you change your select assignment to get the actual element, like so:

...
var $carousel = $('.slick-slider');
var select;
select = $("#select").change(function() {
    goTo = select.selectedIndex;
    $carousel.slick("goTo", goTo);
})[0];// array notation returns native
...

then the rest of your code should work without the need to use prop().




回答3:


to reference the index of the option selected use

goTo = $("#select option:selected").index();


来源:https://stackoverflow.com/questions/41812958/slick-carousel-sync-to-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!