如何重新呈现 owl-轮播项目?

How to re-render a owl-carousel item?

好吧,我现在正在使用 owl-carousel-2 插件。

我遇到了以下问题:

标记代码:

<div class="owl-carousel" style="display: none;">
    <div class="item"><img src="..." /></div>
    <div class="item"><img src="..." /></div>
    <!-- ... -->
    <div class="item"><img src="..." /></div>
</div>

<script>
$(function() {
    var $owl = $('.owl-carousel');
    $owl.owlCarousel();

    // Doing many things here.

    $owl.show();
});
</script>

问题是:

当我用$owl.owlCarousel();语句初始化时,在隐藏状态下,它的大小没有被初始化。

所以我显示那个控件的时候,控件显示的很乱!

但是当我调整 window 的大小时,它似乎触发了重新渲染。控件渲染内容,然后显示良好。


所以我想知道是否有办法在其上触发此重新渲染(或刷新)方法。

为了保证控件不会乱显示。

我尝试阅读文档和来源,但还没有一个好的解决方案。

请帮忙。

你有没有看你使用的插件的文档,因为owl轮播在你想更新轮播的时候有一个refresh的方法

refresh.owl.carousel

Type: attachable, cancelable, triggerable
Callback: onRefresh
Parameter: [event, speed]

docs are here 事件

我发现了一个丑陋、肮脏的解决方案。无论如何,它奏效了:

主要程序:

  1. 摧毁那个 owl-旋转木马。
  2. 手动将标记更改为初始状态。
  3. 初始化 owl-carousel。

var $owl = $('.owl-carousel');
$owl.trigger('destroy.owl.carousel');
// After destory, the markup is still not the same with the initial.
// The differences are:
//   1. The initial content was wrapped by a 'div.owl-stage-outer';
//   2. The '.owl-carousel' itself has an '.owl-loaded' class attached;
//   We have to remove that before the new initialization.
$owl.html($owl.find('.owl-stage-outer').html()).removeClass('owl-loaded');
$owl.owlCarousel({
    // your initial option here, again.
});

它起作用了,但是以一种肮脏的方式。希望看到更好、更简洁的解决方案。

运行 进入与 OP 相同的问题。我设法通过首先删除 owl-loaded class 来让它工作。然后在渲染时,在重新添加 class 后触发刷新事件。

// Remove the owl-loaded class after initialisation 
$owl.owlCarousel().removeClass('owl-loaded');

// Show the carousel and trigger refresh
$owl.show(function() {
  $(this).addClass('owl-loaded').trigger('refresh.owl.carousel');
})

这对我有用:

// get owl element
var owl = $('.owl-carousel');

// get owl instance from element
var owlInstance = owl.data('owlCarousel');

// if instance is existing
if(owlInstance != null)
    owlInstance.reinit();

更多信息:http://owlgraphic.com/owlcarousel/demos/manipulations.html

这是我的解决方案,基于 fish_ball 的巧妙解决方法:

if($('.owl-carousel').hasClass('owl-theme')){ //resize event was triggering an error, this if statement is to go around it

            $('.owl-carousel').trigger('destroy.owl.carousel'); //these 3 lines kill the owl, and returns the markup to the initial state
            $('.owl-carousel').find('.owl-stage-outer').children().unwrap();
            $('.owl-carousel').removeClass("owl-center owl-loaded owl-text-select-on");

            $(".owl-carousel").owlCarousel(); //re-initialise the owl
        }

至于 2.0.0-beta.2.4 这对我有用:

var $owl = $('.owl-carousel');
if ($owl.data('owlCarousel')) {
    $owl.data('owlCarousel').onThrottledResize();
}

对于 Owl 轮播 2,您可以像这样重新初始化:

jQuery('.owl-carousel').trigger('refresh.owl.carousel');

参见 this issue