w3h5

swiper宽度超出后自动适应的tab关联切换导航

今天需要写一个 tab 切换,上面一个可以左右滑动,点击上面的 tab 块,下面的跟着切换。

swiper.png swiper宽度超出后自动适应的tab关联切换导航 经验总结

其实 swiper 就可以实现,代码如下:

HTML:

<div class="container">
    <div class="swiper-container" id="swiper-container1">
        <div class="swiper-wrapper">
            <div class="swiper-slide active-nav">
                版块1
            </div>
            <div class="swiper-slide">
                版块2
            </div>
            <div class="swiper-slide">
                版块3
            </div>
            <div class="swiper-slide">
                版块4
            </div>
            <div class="swiper-slide">
                版块5
            </div>
            <div class="swiper-slide">
                版块6
            </div>
            <div class="swiper-slide">
                版块7
            </div>
            <div class="swiper-slide">
                版块8
            </div>
        </div>
    </div>
    <div class="swiper-container" id="swiper-container2">
        <div class="swiper-wrapper">
            <div class="swiper-slide blue-slide">slider1</div>
            <div class="swiper-slide red-slide">slider2</div>
            <div class="swiper-slide orange-slide">slider3</div>
            <div class="swiper-slide green-slide">slider4</div>
            <div class="swiper-slide pink-slide">slider5</div>
            <div class="swiper-slide blue-slide">slider6</div>
            <div class="swiper-slide red-slide">slider7</div>
            <div class="swiper-slide green-slide">slider8</div>
        </div>
    </div>
</div>

JS:

<script>
    var mySwiper1 = new Swiper('#swiper-container1', {
        watchSlidesProgress: true,
        watchSlidesVisibility: true,
        slideToClickedSlide: true,//点击跟随滑动
        slidesPerView: 4.5,//一屏显示的个数
        onTap: function () {
            mySwiper2.slideTo(mySwiper1.clickedIndex)
        }
    })
    var mySwiper2 = new Swiper('#swiper-container2', {
        onSlideChangeStart: function () {
            updateNavPosition()
        }
    })

    function updateNavPosition() {
        $('#swiper-container1 .active-nav').removeClass('active-nav')
        var activeNav = $('#swiper-container1 .swiper-slide').eq(mySwiper2.activeIndex).addClass('active-nav');
        console.log(activeNav.index())
        if (!activeNav.hasClass('swiper-slide-visible')) {
            if (activeNav.index() > mySwiper1.activeIndex) {
                var thumbsPerNav = Math.floor(mySwiper1.width / activeNav.width()) - 1
                console.log(thumbsPerNav.index())
                mySwiper1.slideTo(activeNav.index() - thumbsPerNav)
            } else {
                mySwiper1.slideTo(activeNav.index())
            }
        }
    }
</script>


声明:本文由w3h5原创,转载请注明出处:《swiper宽度超出后自动适应的tab关联切换导航》 https://www.w3h5.com/post/399.html

赞 (0)
分享到: +More |

评论 沙发

换个身份