The clicked item should be in center in owl carousel

我怕爱的太早我们不能终老 提交于 2019-12-09 22:58:32

问题


$(".owl-carousel").owlCarousel({
    margin:10,
    dots:false,
    nav:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
});

The Above is my Owl carousel. Now i need clicked owl-item should be center. please any me


回答1:


  1. You can trigger the to.owl.carousel event when the user clicks on the item. This event causes the Owl Carousel to move to a specific position.

  2. I've set the data-position attribute for each div inside the carousel before initializing the carousel. Then I use this attribute as a parameter of the to.owl.carousel event.

Please check the result: https://codepen.io/glebkema/details/dWXzza/

var $owl = $('.owl-carousel');

$owl.children().each( function( index ) {
  $(this).attr( 'data-position', index ); // NB: .attr() instead of .data()
});

$owl.owlCarousel({
  center: true,
  loop: true,
  items: 5,
});

$(document).on('click', '.owl-item>div', function() {
  $owl.trigger('to.owl.carousel', $(this).data( 'position' ) ); 
});
.owl-item > div {
  cursor: pointer;
  margin: 9px 12px;
  transition: margin 0.4s ease;
}
.owl-item.center > div {
  cursor: auto;
  margin: 0;
}
<div class="container">
  <div class="owl-carousel">
    <div><img src="//placehold.it/400x300/f06/fff/?text=1" alt=""></div>
    <div><img src="//placehold.it/400x300/f63/fff/?text=2" alt=""></div>
    <div><img src="//placehold.it/400x300/fc3/fff/?text=3" alt=""></div>
    <div><img src="//placehold.it/400x300/693/fff/?text=4" alt=""></div>
    <div><img src="//placehold.it/400x300/3cc/fff/?text=5" alt=""></div>
    <div><img src="//placehold.it/400x300/369/fff/?text=6" alt=""></div>
    <div><img src="//placehold.it/400x300/936/fff/?text=7" alt=""></div>
  </div>
</div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>


来源:https://stackoverflow.com/questions/43510957/the-clicked-item-should-be-in-center-in-owl-carousel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!