slideToClosest.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* eslint no-unused-vars: "off" */
  2. export default function slideToClosest(speed, runCallbacks, internal, threshold) {
  3. if (speed === void 0) {
  4. speed = this.params.speed;
  5. }
  6. if (runCallbacks === void 0) {
  7. runCallbacks = true;
  8. }
  9. if (threshold === void 0) {
  10. threshold = 0.5;
  11. }
  12. const swiper = this;
  13. let index = swiper.activeIndex;
  14. const skip = Math.min(swiper.params.slidesPerGroupSkip, index);
  15. const snapIndex = skip + Math.floor((index - skip) / swiper.params.slidesPerGroup);
  16. const translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate;
  17. if (translate >= swiper.snapGrid[snapIndex]) {
  18. // The current translate is on or after the current snap index, so the choice
  19. // is between the current index and the one after it.
  20. const currentSnap = swiper.snapGrid[snapIndex];
  21. const nextSnap = swiper.snapGrid[snapIndex + 1];
  22. if (translate - currentSnap > (nextSnap - currentSnap) * threshold) {
  23. index += swiper.params.slidesPerGroup;
  24. }
  25. } else {
  26. // The current translate is before the current snap index, so the choice
  27. // is between the current index and the one before it.
  28. const prevSnap = swiper.snapGrid[snapIndex - 1];
  29. const currentSnap = swiper.snapGrid[snapIndex];
  30. if (translate - prevSnap <= (currentSnap - prevSnap) * threshold) {
  31. index -= swiper.params.slidesPerGroup;
  32. }
  33. }
  34. index = Math.max(index, 0);
  35. index = Math.min(index, swiper.slidesGrid.length - 1);
  36. return swiper.slideTo(index, speed, runCallbacks, internal);
  37. }