尝试向 OwlCarousel 添加键盘导航选项

Trying to add Keyboard navigation option to OwlCarousel

默认情况下,OwlCarousel 幻灯片无法使用键盘移动。我使用此代码添加了该功能,但 returns 出现错误。

var owl = $('#carousel-div-id').data('owlCarousel');
$(document.documentElement).keyup(function(event) {
// handle cursor keys
if (event.keyCode == 37) {
    owl.prev();
} else if (event.keyCode == 39) {
    owl.next();
}
});

错误如下

Uncaught ReferenceError: owl is not defined

回答我自己的问题。想要给OwlCarousel增加键盘功能的可以使用下面的方法

//Usual Owlcarousel code.
$(document).ready(function() {
   var owl = $("#owl-example");
   owl.owlCarousel({
       pagination: true
   });

//Following code would do the trick.
 $(document.documentElement).keyup(function (event) {
   if (event.keyCode == 37) {
       owl.trigger('owl.prev');
   } 
   else if (event.keyCode == 39) {
        owl.trigger('owl.next');
   }

 });
});

更新

owl.trigger('owl.prev'), owl.trigger('owl.next') 不适用于 Owl 轮播 2。相反,请使用

 owl.trigger('next.owl.carousel');

owl.trigger('prev.owl.carousel');