programing

이동식 좌/우 스와이프를 이용하여 부트스트랩 회전목마 슬라이더를 만드는 방법

sourcejob 2023. 9. 26. 22:19
반응형

이동식 좌/우 스와이프를 이용하여 부트스트랩 회전목마 슬라이더를 만드는 방법

데모 JSSFIDLE

  <div class="col-md-4">
          <!--Carousel-->
          <div id="sidebar-carousel-1" class="carousel slide" data-ride="carousel">
            <ol class="carousel-indicators grey">
              <li data-target="#sidebar-carousel-1" data-slide-to="0" class="active"></li>
              <li data-target="#sidebar-carousel-1" data-slide-to="1"></li>
              <li data-target="#sidebar-carousel-1" data-slide-to="2"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <a href="" data-lightbox="image-1" title="">
                <img src="http://shrani.si/f/3D/13b/1rt3lPab/2/img1.jpg" alt="...">
                </a>
              </div>
              <div class="item">
                <a href="" data-lightbox="image-1" title="">
                <img src="http://shrani.si/f/S/jE/UcTuhZ6/1/img2.jpg" alt="...">
                </a>                  </div>
              <div class="item">
                <a href="" data-lightbox="image-1" title="">
                <img src="http://shrani.si/f/h/To/1yjUEZbP/img3.jpg" alt="...">
                </a>                  </div>
            </div>
             <!-- Controls -->
        <a class="left carousel-control" href="#sidebar-carousel-1" data-slide="prev">
          <span class="glyphicon glyphicon-chevron-left"></span>
        </a>
        <a class="right carousel-control" href="#sidebar-carousel-1" data-slide="next">
          <span class="glyphicon glyphicon-chevron-right"></span>
        </a>
                  </div><!--/Carousel--></div>

제가 하고 싶은 일은 모바일 기기에만 좌/우 터치 스와이프 기능을 추가하는 것입니다.내가 어떻게 그럴 수 있을까?

또한 호버에 나타나는 이전/다음 단추를 모바일/아이패드 버전에서 더 작게 만드는 방법은 무엇입니까?

감사해요.

파티에 좀 늦었지만, 제가 사용한 jQuery는 다음과 같습니다.

$('.carousel').on('touchstart', function(event){
    const xClick = event.originalEvent.touches[0].pageX;
    $(this).one('touchmove', function(event){
        const xMove = event.originalEvent.touches[0].pageX;
        const sensitivityInPx = 5;

        if( Math.floor(xClick - xMove) > sensitivityInPx ){
            $(this).carousel('next');
        }
        else if( Math.floor(xClick - xMove) < -sensitivityInPx ){
            $(this).carousel('prev');
        }
    });
    $(this).on('touchend', function(){
        $(this).off('touchmove');
    });
});

jQuery mobile이나 다른 플러그인이 필요 없습니다.스와이프의 감도를 조정해야 하는 경우5그리고.-5.

저는 최근에 작업하던 프로젝트에 이 기능을 추가해야 했는데 이 문제를 해결하기 위해 jQuery Mobile을 추가하는 것이 오버킬처럼 느껴져서 해결책을 생각해 github: bcSwipe(부트스트랩 회전목마 스와이프)에 올렸습니다.

경량의 jQuery 플러그인(8kb에서 jQuery Mobile 터치 이벤트 대비 ~600바이트 미니드 대 jQuery Mobile 터치 이벤트)이며 안드로이드와 iOS에서 테스트를 거쳤습니다.

사용 방법은 이렇습니다.

$('.carousel').bcSwipe({ threshold: 50 });

업데이트:

저는 웹 디자인을 처음 접했을 때 이 해결책을 생각해 냈습니다.제가 나이가 들고 현명해졌으니 리암이 한 대답이 더 나은 선택인 것 같습니다.더 생산적인 솔루션인 다음 상위 답변을 보십시오.

저는 최근에 프로젝트를 진행했는데 이 예시는 완벽하게 들어맞았습니다.아래 링크를 드립니다.

먼저 jQuery mobile을 추가해야 합니다.

http://jquerymobile.com/

이렇게 하면 터치 기능이 추가되고 스와이프와 같은 이벤트를 수행하기만 하면 됩니다.

<script>
$(document).ready(function() {
   $("#myCarousel").swiperight(function() {
      $(this).carousel('prev');
    });
   $("#myCarousel").swipeleft(function() {
      $(this).carousel('next');
   });
});
</script>

제가 사용한 자습서를 찾을 수 있는 링크는 아래와 같습니다.

http://lazcreative.com/blog/how-to/how-to-adding-swipe-support-to-bootstraps-carousel/

부트스트랩 4.2는 이제 매우 쉬워졌습니다. 회전목마 디바에서 터치 옵션을 통과하기만 하면 됩니다.data-touch="true", Boolean 값만 허용하기 때문입니다.

당신의 경우와 같이 부트스트랩을 4.2로 업데이트하고 다음을 정확한 순서로 붙여넣기(또는 다운로드 소스 파일)합니다.

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

그런 다음 부트스트랩 회전목마 디브에 터치 옵션을 추가합니다.

    <div id="sidebar-carousel-1" class="carousel slide" data-ride="carousel" data-touch="true">

다음 솔루션 참조:부트스트랩 터치 회전목마.Twitter Bootstrap의 Carousel(v3)이 터치 장치에서 제스처를 가능하게 하는 드롭인 완벽함.http://ixisio.github.io/bootstrap-touch-carousel/

사용하지 않으실 경우jQuery mobile나처럼Hammer.js를 사용할 수 있습니다.

jQuery Mobile불요불급한 암호 없이

$(document).ready(function() {
  Hammer(myCarousel).on("swipeleft", function(){
    $(this).carousel('next');
  });
  Hammer(myCarousel).on("swiperight", function(){
    $(this).carousel('prev');
  });
});

확인된 솔루션은 정확하지 않으며, 마우스 오른쪽 버튼을 누르면 오른쪽 스와이프가 트리거됩니다. 스와이프를 위해 다른 플러그인을 시도한 후 거의 완벽한 솔루션을 찾았습니다.

터치 스와이프

이 플러그인은 미래 요소를 지원하지 않기 때문에 "거의"라고 말했습니다.그래서 우리는 스와이프 내용이 ajax 등에 의해 변경될 때 스와이프 호출을 다시 초기화해야 할 것입니다.이 플러그인은 멀티 손가락 터치, pinch 등과 같은 터치 이벤트로 재생할 수 있는 다양한 옵션이 있습니다.

http://labs.rampinteractive.co.uk/touchSwipe/demos/index.html

해결책 1:

$("#myCarousel").swipe( {
            swipe:function(event, direction, distance, duration, fingerCount, fingerData) {

                if(direction=='left'){
                    $(this).carousel('next');
                }else if(direction=='right'){
                    $(this).carousel('prev');
                }

            }
        });

솔루션 2:(향후 요소 케이스용)

function addSwipeTo(selector){
            $(selector).swipe("destroy");
            $(selector).swipe( {
                swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
                    if(direction=='left'){
                        $(this).carousel('next');
                    }else if(direction=='right'){
                        $(this).carousel('prev');
                    }
                }
            });
}
addSwipeTo("#myCarousel");

5 (2018 10 20 ) 됩니다에 약 5일 됩니다.
://

https:// deploy- preview-25776--twbs-bootstrap4.netlify.com/docs/4.1/components/carousel/

무거운 jQuery 모바일을 사용하는 것보다 선호하는 기능은 회전식 스와이프입니다.github의 source code에 직접 뛰어들어 파일을 복사하는 것을 제안합니다.carousel-swipe.js당신의 프로젝트 디렉토리에.

아래와 같이 스위퍼 이벤트를 사용합니다.

$('#carousel-example-generic').carousel({
      interval: false 
  });

만약 누군가가 이 답변의 각진 버전을 찾고 있다면, 저는 지침을 만드는 것이 좋은 생각이라고 제안하고 싶습니다.

참고: ngx-bootstrap이 사용됩니다.

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;
  }
}

html:

<carousel appCarouselSwipe>

    ...

</carousel>

언급

언급URL : https://stackoverflow.com/questions/21349984/how-to-make-bootstrap-carousel-slider-use-mobile-left-right-swipe

반응형