slideToClosest.js 1.4 KB

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