<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>TAB测试</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css"> <style type="text/css"> * { margin: 0; padding: 0 } li { list-style: none } .box { margin: 50px auto; width: 800px } .swiperTab { display: flex; width: 100%; flex-direction: row; justify-content: center; align-items: center } .swiperTab li { display: flex; height: 48px; border-left: 1px solid #dfdfdf; background-color: #ddf8ff; cursor: pointer; flex: 1; flex-direction: row; justify-content: center; align-items: center } .swiperTab li:first-child { border-left: 1px solid transparent } .swiperTab li.active { background-color: #f60; color: #fff } .swiperTab li:nth-child(1).active { background-color: red; } .swiperTab li:nth-child(2).active { background-color: green; } .swiperTab li:nth-child(3).active { background-color: blue; } .swiper-slide { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 20px } .swiper-slide:nth-child(1) { height: 300px; background-color: red; } .swiper-slide:nth-child(2) { height: 300px; background-color: green } .swiper-slide:nth-child(3) { height: 300px; background-color: blue; } </style> </head> <body> <div class="box"> <ul class="swiperTab"> <li> <span>TAB-01</span> </li> <li> <span>TAB-02</span> </li> <li> <span>TAB-03</span> </li> </ul> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide">111111111111111</div> <div class="swiper-slide">222222222222222</div> <div class="swiper-slide">333333333333333</div> </div> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.min.js"></script> <script type="text/javascript"> function tabs(obj, swiperObj, className, index) { var tabSwiper = new Swiper(swiperObj, { initialSlide: index, // 设定初始化时slide的索引 speed: 500, //滑动速度,单位ms autoHeight: true, //高度随内容变化 onSlideChangeStart: function() { if (tabSwiper) { /*判断tabSwiper是否存在,否则当哈希值不为0的时候会报错 */ $(obj + "." + className).removeClass(className); /*有当前类名的删除类名,给下一个添加当前类名*/ $(obj).eq(tabSwiper.activeIndex).addClass(className); /*activeIndex是过渡后的slide索引*/ } } }); // 模拟点击事件,如果是移入事件,将mousedown 改为 mouseenter $(obj).on('touchstart mousedown', function(e) { e.preventDefault();/*清除默认事件*/ $(obj + "." + className).removeClass(className); $(this).addClass(className);/*点击当前导航 改变当前样式*/ tabSwiper.slideTo($(this).index());/*滑动到对应的滑块*/ }); $(obj).click(function(e) { e.preventDefault();/*清除默认点击事件*/ }); } </script> <script> /*swiper选项卡切换*/ var i=$(this).index(); $(function() { //swiperTab 是你导航的className,active是你当前状态的className $('.swiperTab > li').eq(0).addClass('active'); tabs('.swiperTab > li', '.swiper-container', 'active'); }); </script> </body> </html>
相关分类