Swiper.js — отменить привязку события touchmove на последнем слайде, повторно привязать к touchmove, когда направление вверх

У меня есть некоторый контент под элементом Swiper.js. Я пытаюсь отменить привязку события touchmove к ползунку, чтобы на мобильных устройствах пользователи могли свободно прокручивать страницу вниз, когда они находятся на последнем слайде колоды.

Затем, когда они находятся в верхней части страницы или рядом с ней, или когда верхняя часть элемента swiper равна 0, когда значение window.pageYOffset равно 0, перепривяжите событие касания. Я определяю направление прокрутки, так что это событие, возможно, должно происходить только тогда, когда направление идет вверх.

Swiper предоставляет обратный вызов onReadEnd, который должен оказаться полезным.

Изменить: API также предоставляет onTouchMove и onTouchMoveOpposite.

Соответствующие ссылки

Для правильной отладки используйте ссылку режима отладки и инструменты разработки в мобильном эмуляторе, воздержитесь от использования колесика мыши, используйте только перетаскивание щелчком для имитации событий касания.

Я сделал контейнер swiper высотой 80% для целей отладки — в продакшене он будет иметь высоту 100% окна просмотра.

Не стесняйтесь использовать jQuery в решении, он уже включен в проект.

HTML

<div id="swiper" class="swiper-container">
  <div class="swiper-wrapper">
      <div class="swiper-slide">Slide 1</div>
      <div class="swiper-slide">Slide 2</div>
      <div class="swiper-slide">Slide 3</div>
  </div>
  <div class="swiper-pagination"></div>
</div>

<div class="content">
  <div class="container">
    <h1>Header 1</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias totam vero fuga dolorum explicabo suscipit aliquam hic blanditiis soluta officiis, corrupti consequatur nostrum sint possimus neque eos temporibus amet placeat.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias totam vero fuga dolorum explicabo suscipit aliquam hic blanditiis soluta officiis, corrupti consequatur nostrum sint possimus neque eos temporibus amet placeat.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias totam vero fuga dolorum explicabo suscipit aliquam hic blanditiis soluta officiis, corrupti consequatur nostrum sint possimus neque eos temporibus amet placeat.</p>
    <h2>Header 2</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias totam vero fuga dolorum explicabo suscipit aliquam hic blanditiis soluta officiis, corrupti consequatur nostrum sint possimus neque eos temporibus amet placeat.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias totam vero fuga dolorum explicabo suscipit aliquam hic blanditiis soluta officiis, corrupti consequatur nostrum sint possimus neque eos temporibus amet placeat.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias totam vero fuga dolorum explicabo suscipit aliquam hic blanditiis soluta officiis, corrupti consequatur nostrum sint possimus neque eos temporibus amet placeat.</p>
  </div>
</div>

CSS

html, body {
  position: relative;
  height: 100%;
}
body {
  background: #eee;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 14px;
  color:#000;
  margin: 0;
  padding: 0;
}
.swiper-container {
  width: 100%;
  height: 80%;
}
.swiper-slide {
  text-align: center;
  font-size: 22px;
  background: #fff;

  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;

  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

.content {
  padding: 30px 15px;
}

.container {
  max-width: 1200px;
  margin:0 auto;
}

Javascript

var $el = {
  swiper: document.getElementById('swiper')
}

var swiper = new Swiper('.swiper-container', {
  pagination: '.swiper-pagination',
  paginationClickable: true,
  direction: 'vertical',
  onReachEnd: function(swiperInstance) {
    console.log('onReachEnd(), unbind touchmove')
  },
  onTouchMove: function(swiper, event) {
    // Callback function, will be executed when user touch and move finger over Swiper. Receives swiper instance and 'touchmove' event as an arguments.
  },
  onTouchMoveOpposite: function(swiper, event) {
    //  Callback function, will be executed when user touch and move finger over Swiper in direction opposite to direction parameter. Receives swiper instance and 'touchmove' event as an arguments.
  }
});



// Unsure if below will be needed, could be done all within swiper callbacks


var lastY = 0;
$el.swiper.addEventListener('touchmove', function(event) {
  var currentY = event.touches[0].clientY;
  if ( currentY > lastY ) {
    console.log('up', currentY, lastY)

    // top of page +/- 100px
    // this is inaccurate, currentY is the Y pos of the touch, not
    // equivalent to window.pageYOffset or scrollTop
    if ( currentY <= 100 ) {
      console.log('top of page, rebind touchmove')
    }

  } else if( currentY < lastY ) {
    console.log('down')
  }
  lastY = currentY;
})

person elzi    schedule 12.08.2016    source источник


Ответы (1)


Я работаю над сайтом, где у меня была похожая ситуация. Вы должны установить свойство mousewheelControl: true при инициализации, чтобы вы могли использовать методы .disableMousewheelControl() и .enableMousewheelControl().

Ссылка на пробный сайт примера: http://multiply.website.2017.360southclients.net:8080/services/seo/

Ниже приведен соответствующий код JS. (к вашему сведению, расчеты freezePoint учитывают липкую панель навигации и элементы размером vh над слайд-шоу)

var serviceSwiper = new Swiper( '.swiper-container', {
  direction: 'vertical',
  slidesPerView: 1,
  mousewheelControl: true,
  mousewheelReleaseOnEdges: true,
  mousewheelSensitivity: .05,
  ...
});

serviceSwiper.disableMousewheelControl();

var freezePoint = 0;

$( window ).on( 'resize', function( e ) {
  freezePoint = Math.ceil( $( '#service-slides' ).offset().top - $( '#header' ).outerHeight() - 50 );
}).trigger( 'resize' );

$( window ).on( 'scroll', function( e ) {
  if ( ! serviceSwiper.isEnd && window.scrollY >= freezePoint || ! serviceSwiper.isBeginning && window.scrollY <= freezePoint ) {
    $( 'html' ).scrollTop( freezePoint );
    if ( ! serviceSwiper.params.mousewheelControl ) {
      serviceSwiper.enableMousewheelControl();
    }
  } else if ( serviceSwiper.params.mousewheelControl ) {
    serviceSwiper.disableMousewheelControl();
  }
});
person atstormcup    schedule 13.09.2017