简体   繁体   English

如何在页面加载时将 class 添加到 Owl-item?

[英]How can I add class to Owl-item on page load?

I am trying to add custom classes "Big, Medium, Medium" to 3 different owl-items.我正在尝试将自定义类“大、中、中”添加到 3 个不同的猫头鹰项目。 But this only works when it autoplays.但这仅在自动播放时有效。 It doesn't work when you see it for the first time.当你第一次看到它时,它不起作用。 How can I run this code on page load also?如何在页面加载时运行此代码?

 $('#MySlider .owl-carousel').on('translate.owl.carousel', function(e){
    idx = e.item.index;
    $('#MySlider .owl-carousel').find('.owl-item.big').removeClass('big');
    $('#MySlider .owl-carousel').find('.owl-item.medium').removeClass('medium');
    $('#MySlider .owl-carousel').find('.owl-item').eq(idx).addClass('big');
    $('#MySlider .owl-carousel').find('.owl-item').eq(idx+1).addClass('medium');
    $('#MySlider .owl-carousel').find('.owl-item').eq(idx+2).addClass('medium');
 });

I would like my code to look like this on page load, so that I can style the carousel items.我希望我的代码在页面加载时看起来像这样,这样我就可以设置轮播项目的样式。 But it only adds the classes after it starts the autoplay.但它只在开始自动播放后添加类。

  <div class="owl-carousel">
      <div class="owl-item big active">...</div>
      <div class="owl-item medium active">...</div>
      <div class="owl-item medium active">...</div>
      <div class="owl-item">...</div>
      <div class="owl-item">...</div>
  </div>

You can use onInitialized callback.您可以使用onInitialized回调。 This is called when the plugin has been initialized.这在插件初始化时调用。

$(".owl-carousel").owlCarousel({
  items: 1,
  loop: true,
  dots: false,
  onInitialized: function(event) {
    let element = jQuery(event.target);
    let idx = event.item.index;
    element.find('.owl-item.big').removeClass('big');
    element.find('.owl-item.medium').removeClass('medium');
    element.find('.owl-item').eq(idx).addClass('big');
    element.find('.owl-item').eq(idx + 1).addClass('medium');
    element.find('.owl-item').eq(idx + 2).addClass('medium');
  },
  navContainer: '#nav',
});

Or you can use the event:或者您可以使用该事件:

 $('#MySlider .owl-carousel').on('initialized.owl.carousel', function(event) {
    let element = jQuery(event.target);
    let idx = event.item.index;
    element.find('.owl-item.big').removeClass('big');
    element.find('.owl-item.medium').removeClass('medium');
    element.find('.owl-item').eq(idx).addClass('big');
    element.find('.owl-item').eq(idx + 1).addClass('medium');
    element.find('.owl-item').eq(idx + 2).addClass('medium');
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM