Slick.js垂直模式下centerMode与slidesToShow>5兼容问题求助
Great catch! This is a known inconsistency in Slick.js when combining vertical: true and centerMode: true—the initial centering logic was built primarily for horizontal sliders, so it fails to correctly calculate the middle slide position in vertical orientation, especially with an odd number of slidesToShow. Let’s break down the problem and actionable solutions:
Reproducible Code
HTML
<section class="slider"> <div>slide1</div> <div>slide2</div> <div>slide3</div> <div>slide4</div> <div>slide5</div> <div>slide6</div> <div>slide7</div> <div>slide8</div> <div>slide9</div> <div>slide10</div> <div>slide11</div> <div>slide12</div> </section>
SCSS
$c1: #3a8999; $c2: #e84a69; .slider { width: auto; margin: 30px 50px 50px; } .slick-slide { background: $c1; color: white; padding: 40px 0; font-size: 30px; font-family: "Arial", "Helvetica"; text-align: center; } .slick-prev:before, .slick-next:before { color: black; } .slick-dots { bottom: -30px; } .slick-slide:nth-child(odd) { background: $c2; }
jQuery
$(".slider").slick({ autoplay: false, dots: true, vertical: true, slidesToShow: 7, slidesToScroll: 1, centerMode: true });
Why This Happens
Slick’s centerMode logic doesn’t adjust its initial slide calculation for vertical layouts. For slidesToShow: 7 (an odd number), the true center should be slide3 (zero-based index 2), but the library incorrectly applies the slick-center class to the first slide instead.
Solutions
1. Explicitly Set the Initial Slide
The simplest fix is to define the initialSlide option to target the middle slide directly. For slidesToShow:7, the middle index is 2:
$(".slider").slick({ autoplay: false, dots: true, vertical: true, slidesToShow: 7, slidesToScroll: 1, centerMode: true, initialSlide: 2 // Starts with slide3 centered });
2. Dynamic Calculation for Flexibility
If you might update slidesToShow later, use the init callback to calculate and set the center dynamically:
$(".slider").slick({ autoplay: false, dots: true, vertical: true, slidesToShow: 7, slidesToScroll: 1, centerMode: true }).on('init', function() { const $slider = $(this); const slidesToShow = $slider.slick('getOption', 'slidesToShow'); const centerIndex = Math.floor(slidesToShow / 2); // Correct the slick-center class and scroll position $slider.find('.slick-center').removeClass('slick-center'); $slider.find('.slick-slide').eq(centerIndex).addClass('slick-center'); $slider.slick('slickGoTo', centerIndex); });
This approach adapts automatically if you change slidesToShow, making it more maintainable.
内容的提问来源于stack exchange,提问作者Mateusz Pączkowski

