Как переключать слайды в owl-carousel стрелками клавиатуры?

432
08 июля 2017, 11:27

В документации к библиотеке не нашел реализации прокрутки слайдов стрелками клавиатуры. Как это можно реализовать?
Нужно чтобы при нажатии на стрелку вверх и стрелку вправо переключалось на следующий по очереди слайд, при нажатии на стрелку вниз и влево - соответственно на предыдущий. Плюс, при скроллинге вниз и вверх на мобильных и планшетах слайды тоже должны свайпиться, пока-что удалось только реализовать эффект анимации скролла вниз-вверх(animateOut: "slideOutUp",animateIn: "slideInUp")

Слайдер:

<article class="owl-carousel main-carousel hidden-xs hidden-sm">
    <section class="portfolio-slide">
        <div class="col-xs-12 portfolio-slide-content">
            <div class="col-xs-12 work-img-block">
                <img src="img/beekeper_thumb.png" class="img-responsive work-img">
            </div>
            <div class="col-xs-12 work-info">
                <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1>
                <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p>
                <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p>
                <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p>
                <p class="work-info-text ">The application works with no access to the Internet.</p>
                <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p>
                <div class="col-xs-12 apps-button">
                    <a href="#" class="playmarket-button">Link to Google Play</a>
                    <a href="#" class="appstore-button">Link to AppStore</a>
                </div>
            </div>
        </div>
    </section>
    <section class="portfolio-slide">
        <div class="col-xs-12 col-sm-6 portfolio-slide-content">
            <div class="col-xs-8 work-img-block">
                <img src="img/beekeper_thumb.png" class="img-responsive work-img">
            </div>
            <div class="col-xs-8 work-info">
                <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1>
                <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p>
                <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p>
                <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p>
                <p class="work-info-text ">The application works with no access to the Internet.</p>
                <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p>
                <div class="col-xs-12 apps-button">
                    <a href="#" class="playmarket-button">Link to Google Play</a>
                    <a href="#" class="appstore-button">Link to AppStore</a>
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-6 portfolio-slide-content">
            <div class="col-xs-8 work-img-block">
                <img src="img/studnet_support_thumb.png" class="img-responsive work-img">
            </div>
            <div class="col-xs-8 work-info">
                <h1 class="text-center col-xs-12 work-info-header">Studnet</h1>
                <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p>
                <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p>
                <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p>
                <p class="work-info-text">The application works with no access to the Internet.</p>
                <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p>
                <div class="col-xs-12 apps-button">
                    <a href="#" class="playmarket-button">Link to Google Play</a>
                    <a href="#" class="appstore-button">Link to AppStore</a>
                </div>
            </div>
        </div>
    </section>
    <section class="portfolio-slide">
        <div class="col-xs-12 col-sm-4 portfolio-slide-content">
            <div class="col-xs-12 work-img-block">
                <img src="img/beekeper_thumb.png" class="img-responsive work-img">
            </div>
            <div class="col-xs-12 work-info">
                <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1>
                <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p>
                <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p>
                <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p>
                <p class="work-info-text ">The application works with no access to the Internet.</p>
                <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p>
                <div class="col-xs-12 apps-button">
                    <a href="#" class="playmarket-button">Link to Google Play</a>
                    <a href="#" class="appstore-button">Link to AppStore</a>
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-4 portfolio-slide-content">
            <div class="col-xs-12  work-img-block">
                <img src="img/studnet_support_thumb.png" class="img-responsive work-img">
            </div>
            <div class="col-xs-12 work-info">
                <h1 class="text-center col-xs-12 work-info-header">Studnet</h1>
                <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p>
                <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p>
                <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p>
                <p class="work-info-text">The application works with no access to the Internet.</p>
                <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p>
                <div class="col-xs-12 apps-button">
                    <a href="#" class="playmarket-button">Link to Google Play</a>
                    <a href="#" class="appstore-button">Link to AppStore</a>
                </div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-4 portfolio-slide-content">
            <div class="col-xs-12 work-img-block">
                <img src="img/gulfstream_app_thumb.png" class="img-responsive work-img">
            </div>
            <div class="col-xs-12 work-info">
                <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1>
                <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p>
                <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p>
                <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p>
                <p class="work-info-text">The application works with no access to the Internet.</p>
                <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p>
                <div class="col-xs-12 apps-button">
                    <a href="#" class="playmarket-button">Link to Google Play</a>
                    <a href="#" class="appstore-button">Link to AppStore</a>
                </div>
            </div>
        </div>
    </section>
</article>


Инициализация и настройка через owl-carousel:

<script>
    $(document).ready(function(){
        var owl = $(".main-carousel");
        owl.owlCarousel({
            items:1,
            loop:true,
            nav: true,
            dots: true,
            autoplay:false,
            autoplayTimeout:5000,
            autoplayHoverPause:true
        });
        owl.on('mousewheel', '.owl-stage', function (e) {
            if (e.deltaY>0) {
                owl.trigger('next.owl');
            } else {
                owl.trigger('prev.owl');
            }
            e.preventDefault();
        });
    });
    $(document).ready(function(){
        var owl = $(".mobile-carousel");
        owl.owlCarousel({
            items:1,
            loop:true,
            nav: true,
            dots: true,
            animateOut: "slideOutUp",
            animateIn: "slideInUp",
            autoplay:false,
            autoplayTimeout:5000,
            autoplayHoverPause:true
        });
        owl.on('mousewheel', '.owl-stage', function (e) {
            if (e.deltaY>0) {
                owl.trigger('next.owl');
            } else {
                owl.trigger('prev.owl');
            }
            e.preventDefault();
        });
    });
</script>
Answer 1

Разобравшись, узнал как можно сделать прокрутку стрелками клавиатуры, если вдруг кому интересно - оставлю тут.

Итак, в моем случае в место инициализации функции надо добавить что-то вроде:

$('body').keydown(function(event) {
            if (event.keyCode == 37) {
                //влево
                owl.trigger('prev.owl');
            }
            if (event.keyCode == 38) {
                //вверх
                owl.trigger('prev.owl');
            }
            if (event.keyCode == 39) {
                //вправо
                owl.trigger('next.owl');
            }
            if (event.keyCode == 40) {
                //вправо
                owl.trigger('next.owl');
            }
        });

А полный код инициализацации, в моем случае, выглядит примерно так:

$(document).ready(function(){
        var owl = $(".main-carousel");
        owl.owlCarousel({
            items:1,
            loop:true,
            nav: true,
            dots: true,
            autoplay:false,
            autoplayTimeout:5000,
            autoplayHoverPause:true
        });
        owl.on('mousewheel', '.owl-stage', function (e) {
            if (e.deltaY>0) {
                owl.trigger('next.owl');
            } else {
                owl.trigger('prev.owl');
            }
        });
        $('body').keydown(function(event) {
            if (event.keyCode == 37) {
                //влево
                owl.trigger('prev.owl');
            }
            if (event.keyCode == 38) {
                //вверх
                owl.trigger('prev.owl');
            }
            if (event.keyCode == 39) {
                //вправо
                owl.trigger('next.owl');
            }
            if (event.keyCode == 40) {
                //вправо
                owl.trigger('next.owl');
            }
        });
    });

Остается актуальным вопросом: как сделать прокрутку при свайпе вниз/вверх в мобильной версии? Если найду решение - кину сюда.

Answer 2

Пример прокрутки по нажатию стрелок влево/вправо:

var owl = $(".main-carousel"); 
owl.owlCarousel({ 
  items: 1, 
  loop: true, 
  nav: true, 
  dots: true, 
  autoplay: false, 
  autoplayTimeout: 5000, 
  autoplayHoverPause: true 
}); 
owl.on('mousewheel', '.owl-stage', function(e) { 
  if (e.deltaY < 0) { 
    owl.trigger('prev.owl'); 
  } else { 
    owl.trigger('next.owl'); 
  } 
  e.preventDefault(); 
}); 
owl.on('mouseover mouseout', function() { 
  $(this).toggleClass('keydown'); 
}); 
$(document).keydown(function(e) { 
  if (owl.hasClass('keydown')) { 
    if (e.keyCode == '39') { 
      owl.trigger('next.owl'); 
    } else if (e.keyCode == '37') { 
      owl.trigger('prev.owl'); 
    } 
  } 
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet" /> 
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet" /> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script src="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/owl.carousel.js"></script> 
<article class="owl-carousel main-carousel hidden-xs hidden-sm"> 
  <section class="portfolio-slide"> 
    <div class="col-xs-12 portfolio-slide-content"> 
      <div class="col-xs-12 work-img-block"> 
        <img src="img/beekeper_thumb.png" class="img-responsive work-img"> 
      </div> 
      <div class="col-xs-12 work-info"> 
        <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1> 
        <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p> 
        <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p> 
        <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p> 
        <p class="work-info-text ">The application works with no access to the Internet.</p> 
        <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p> 
        <div class="col-xs-12 apps-button"> 
          <a href="#" class="playmarket-button">Link to Google Play</a> 
          <a href="#" class="appstore-button">Link to AppStore</a> 
        </div> 
      </div> 
    </div> 
  </section> 
  <section class="portfolio-slide"> 
    <div class="col-xs-12 col-sm-6 portfolio-slide-content"> 
      <div class="col-xs-8 work-img-block"> 
        <img src="img/beekeper_thumb.png" class="img-responsive work-img"> 
      </div> 
      <div class="col-xs-8 work-info"> 
        <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1> 
        <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p> 
        <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p> 
        <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p> 
        <p class="work-info-text ">The application works with no access to the Internet.</p> 
        <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p> 
        <div class="col-xs-12 apps-button"> 
          <a href="#" class="playmarket-button">Link to Google Play</a> 
          <a href="#" class="appstore-button">Link to AppStore</a> 
        </div> 
      </div> 
    </div> 
    <div class="col-xs-12 col-sm-6 portfolio-slide-content"> 
      <div class="col-xs-8 work-img-block"> 
        <img src="img/studnet_support_thumb.png" class="img-responsive work-img"> 
      </div> 
      <div class="col-xs-8 work-info"> 
        <h1 class="text-center col-xs-12 work-info-header">Studnet</h1> 
        <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p> 
        <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p> 
        <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p> 
        <p class="work-info-text">The application works with no access to the Internet.</p> 
        <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p> 
        <div class="col-xs-12 apps-button"> 
          <a href="#" class="playmarket-button">Link to Google Play</a> 
          <a href="#" class="appstore-button">Link to AppStore</a> 
        </div> 
      </div> 
    </div> 
  </section> 
  <section class="portfolio-slide"> 
    <div class="col-xs-12 col-sm-4 portfolio-slide-content"> 
      <div class="col-xs-12 work-img-block"> 
        <img src="img/beekeper_thumb.png" class="img-responsive work-img"> 
      </div> 
      <div class="col-xs-12 work-info"> 
        <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1> 
        <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p> 
        <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p> 
        <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p> 
        <p class="work-info-text ">The application works with no access to the Internet.</p> 
        <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p> 
        <div class="col-xs-12 apps-button"> 
          <a href="#" class="playmarket-button">Link to Google Play</a> 
          <a href="#" class="appstore-button">Link to AppStore</a> 
        </div> 
      </div> 
    </div> 
    <div class="col-xs-12 col-sm-4 portfolio-slide-content"> 
      <div class="col-xs-12  work-img-block"> 
        <img src="img/studnet_support_thumb.png" class="img-responsive work-img"> 
      </div> 
      <div class="col-xs-12 work-info"> 
        <h1 class="text-center col-xs-12 work-info-header">Studnet</h1> 
        <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p> 
        <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p> 
        <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p> 
        <p class="work-info-text">The application works with no access to the Internet.</p> 
        <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p> 
        <div class="col-xs-12 apps-button"> 
          <a href="#" class="playmarket-button">Link to Google Play</a> 
          <a href="#" class="appstore-button">Link to AppStore</a> 
        </div> 
      </div> 
    </div> 
    <div class="col-xs-12 col-sm-4 portfolio-slide-content"> 
      <div class="col-xs-12 work-img-block"> 
        <img src="img/gulfstream_app_thumb.png" class="img-responsive work-img"> 
      </div> 
      <div class="col-xs-12 work-info"> 
        <h1 class="text-center col-xs-12 work-info-header">BeeKeeper</h1> 
        <p class="work-info-text">The beekeeper's handbook with online-store. Developed by a private order. </p> 
        <p class="work-info-text hidden-xs">To upgrade and update the data you only need to connect to the network.</p> 
        <p class="work-info-text hidden-xs">It contains the necessary knowledge base of skilled beekeepers.</p> 
        <p class="work-info-text">The application works with no access to the Internet.</p> 
        <p class="work-info-text hidden-xs">So it is very comfortable to be used in the "field" conditions.</p> 
        <div class="col-xs-12 apps-button"> 
          <a href="#" class="playmarket-button">Link to Google Play</a> 
          <a href="#" class="appstore-button">Link to AppStore</a> 
        </div> 
      </div> 
    </div> 
  </section> 
</article>

Для прокрутки по свайпу предлагаю использовать TouchSwipe.

К сожалению, в сниппете не получается, воспроизвести данный пример:

var owl = $(".mobile-carousel");
owl.owlCarousel({
  items: 1,
  loop: true,
  nav: true,
  dots: true,
  mouseDrag:false,
  pullDrag:false,
  touchDrag:false,
  freeDrag:false
});
owl.swipe({
  swipe: function(event, direction, distance, duration, fingerCount, fingerData) {
    if (direction == 'down') {
     owl.trigger('owl.next');
    }
    if (direction == 'up') {
     owl.trigger('owl.prev');
    }
  },
  threshold: 60,
  allowPageScroll: 'vertical'
});
READ ALSO
Первый элемент с классом

Первый элемент с классом

Подскажите, где ошибся

242
Генерация текстов

Генерация текстов

Добрый день всем!

261
Перебор цикла для вывода списка (постов например) Вордпресс

Перебор цикла для вывода списка (постов например) Вордпресс

Всем приветРаботаю сейчас с Вордпрессом и столкнулся с проблемой

198
Падает php-cgi на Windows Server 2012r2

Падает php-cgi на Windows Server 2012r2

Имеется рабочий (проверен на Debian 8, Windows 10) конфиг Nginx+php+postgresЗапускаю nginx + php-cgi

350