切换Tab时Flickity不会初始化

时间:2019-07-29 14:16:44

标签: javascript slider resize carousel flickity

我在多个vanilla js选项卡中安装了flickity,并在第一个选项卡中正确初始化了它。加载第一个标签的内容时,第二个标签的内容未正确初始化。

<div class="outer-wrap">

<ul class="simple-tabs" id="demo-tabs">
    <li class="tab-1 active">tab-1</li>
    <li class="tab-2">tab-2</li>
    <li class="tab-3">tab-3</li>
</ul>
<div class="clear-float"></div>

<div id="tab-1" class="tab-page active-page"><div class="carousel" data-flickity><div class="carousel-cell"></div><div class="carousel-cell"></div><div class="carousel-cell"></div></div></div>

<div id="tab-2" class="tab-page">
   <div class="carousel" data-flickity><div class="carousel-cell"></div><div class="carousel-cell"></div><div class="carousel-cell"></div></div></div>

<div id="tab-3" class="tab-page">
    <div class="carousel" data-flickity><div class="carousel-cell"></div><div class="carousel-cell"></div><div class="carousel-cell"></div></div></div></div>

JS

<script src="https://cdnjs.cloudflare.com/ajax/libs/flickity/2.2.1/flickity.pkgd.min.js"></script><script>var SimpleTabs = function (elem) {
var activeTabObject;

var TabObject = function () {
    var self = this;
    this.tab; //element
    this.pane; //element
    this.setClick = function () {
        self.tab.addEventListener('click', self.showThisTab)
    };

    this.showThisTab = function () {
        if (self !== activeTabObject) {
            //change the tab page and update the active tab
            activeTabObject.pane.className = activeTabObject.pane.className.replace('active-page', '');
            activeTabObject.tab.className = activeTabObject.tab.className.replace('active', '');
            self.pane.className = self.pane.className + ' active-page';
            self.tab.className = self.tab.className + ' active';
            activeTabObject = self;
        }
    };

};

var ul = elem;
var i;
var items = ul.getElementsByTagName("li");
for (i = 0; i < items.length; ++i) {
    var tab = new TabObject();
    tab.tab = items[i];
    var classString = items[i].className;
    var className = classString.split(' ')[0];
    tab.pane = document.getElementById(className);
    tab.setClick();
    if (classString.indexOf('active') > -1) {
        activeTabObject = tab;
    }  
}
};</script><script>        
    window.onload = function() {
        var demoTabs = new SimpleTabs(document.getElementById('demo-tabs'));
    };
</script>

第二个内容未正确初始化。 codepen:https://codepen.io/himalayanath/pen/xvgyoO 谢谢!

1 个答案:

答案 0 :(得分:0)

根据Flickity document, 您应该在切换标签后调用resize()。