LoginSignup
5
3

More than 3 years have passed since last update.

Slickで `centerMode : true` の時 `slidesToScroll` のオプションは無視される

Last updated at Posted at 2019-12-23

Slickの CenterMode + SlideToScrollでスライダーを動かすと、Slickの仕様でSlideToScrollが無視されてしまいます。
(真ん中寄りで3枚ずつ動かすとかです)

See the Pen slider 1 by Sota Takahashi (@Sota) on CodePen.

$(document).ready(function(){
  const target = $('.slider_box')
  target.slick({
  slidesToShow: 3,
  slidesToScroll: 3,
  dots: false,
  centerMode: true,
  prevArrow: '<button class="prev arrow">←</button>',
  nextArrow: '<button class="next arrow">→</button>'
  });
});

GitHubIssueで2016/05に上がっており、
解決するためにプルリク投げてる方はいるようですが、2019/12ではまだ公式に解決はしていないみたいです…

Core codeを編集しよう☆って言ってる人もいるようですが下記方法で実装できたため覚書です:writing_hand:

そもそも何故起きているのか

公式 Line 529
( https://github.com/kenwheeler/slick/blob/master/slick/slick.js#L529 )

if (_.options.centerMode === true || _.options.swipeToSlide === true) {
    _.options.slidesToScroll = 1;
}

centerMode か swipeToSlide が true のときはslidesToScrollの値が自動で決められてしまうようです。

なので、ここをコメントアウトすれば手っ取り早く解決しますが、他の箇所で影響出てくる可能性があります:no_good:

slickSetOption を使う

指定したオプションを変更するメソッドで、Ver1.4以降で使用可能とのこと。
1.png
methods.png

どのように使用するか

$('.slider').slick('slickSetOption', option, value, refresh);
  • 第1引数(オプション名)
  • 第2引数(オプションの値)
  • 第3引数(boolean / trueの場合動く) (第3引数はオプションなので書かなければtrueになります)

centerModeで3枚ずつ動かすとすれば、

$('.slider').slick("slickSetOption", "slidesToScroll", 3, true);

手順は
1. Slickを動かす
2. 自動でslidesToScrollが1になる
3. 後からslidesToScrollの値を変える
で良さそうです。

実装

$(document).ready(function(){
  const target = $('.slider_box')
  target.slick({
  slidesToShow: 3,
  slidesToScroll: 3,
  dots: false,
  centerMode: true,
  prevArrow: '<button class="prev arrow">←</button>',
  nextArrow: '<button class="next arrow">→</button>'
  });
  target.slick("slickSetOption", "slidesToScroll", 3);
});

See the Pen slider 3 by Sota Takahashi (@Sota) on CodePen.

このメソッドでイベントに合わせてスライダーの挙動を変えたりするのが簡単にできるのでは、と思います。

参考サイト

When centerMode is set to true the slidesToScroll property setting is ignored. #2328
https://github.com/kenwheeler/slick/issues/2328

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3