How to make Bootstrap carousel slider use mobile left/right swipe

前端 未结 10 1061
走了就别回头了
走了就别回头了 2020-11-29 15:49

DEMO JSSFIDDLE

  
10条回答
  •  半阙折子戏
    2020-11-29 16:32

    If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.

    NOTE: ngx-bootstrap is used.

    import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
    import { CarouselComponent } from 'ngx-bootstrap/carousel';
    
    @Directive({
      selector: '[appCarouselSwipe]'
    })
    export class AppCarouselSwipeDirective implements OnInit {
      @Input() swipeThreshold = 50;
      private start: number;
      private stillMoving: boolean;
      private moveListener: Function;
    
      constructor(
        @Host() @Self() @Optional() private carousel: CarouselComponent,
        private renderer: Renderer2,
        private element: ElementRef
      ) {
      }
    
      ngOnInit(): void {
        if ('ontouchstart' in document.documentElement) {
          this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
          this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
        }
      }
    
      private onTouchStart(e: TouchEvent): void {
        if (e.touches.length === 1) {
          this.start = e.touches[0].pageX;
          this.stillMoving = true;
          this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
        }
      }
    
      private onTouchMove(e: TouchEvent): void {
        if (this.stillMoving) {
          const x = e.touches[0].pageX;
          const difference = this.start - x;
          if (Math.abs(difference) >= this.swipeThreshold) {
            this.cancelTouch();
            if (difference > 0) {
              if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
                this.carousel.activeSlide = this.carousel.activeSlide + 1;
              }
            } else {
              if (this.carousel.activeSlide > 0) {
                this.carousel.activeSlide = this.carousel.activeSlide - 1;
              }
            }
          }
        }
      }
    
      private onTouchEnd(e: TouchEvent): void {
        this.cancelTouch();
      }
    
      private cancelTouch() {
        if (this.moveListener) {
          this.moveListener();
          this.moveListener = undefined;
        }
        this.start = null;
        this.stillMoving = false;
      }
    }
    
    

    in html:

    
    
        ...
    
    
    

    Reference

提交回复
热议问题