小程序 tab scrollview 和swiper 的结合

强颜欢笑 提交于 2020-07-26 23:27:06
<!-- <wxs module="fliter" src="../../fliter/fliter.wxs"></wxs> -->
<wxs module="fliter" src="../../../fliter/fliter.wxs"></wxs>
<view>
  <view class='select-title'>
    <text class='skt-rect'>{{listItem.column_name}}</text>
    <view class='select-more skt-rect' bindtap='toAll' data-id="{{listItem.id}}">
      查看全部
      <image class="more" src="../../../img/icon_more@2x.png"></image>
    </view>
  </view>
  <view class="container" wx:if="{{thList}}">
    <scroll-view scroll-x="true" class="tab-h" scroll-with-animation scroll-left="{{scrollLeft}}" wx:if="{{thList.length>1}}">
      <block wx:for="{{thList}}">
        <view class="tab-item {{currentTab===index?'active':''}}" data-current="{{index}}" bindtap="swichNav" data-item="{{item}}">
          {{item.label_name}}
        </view>
      </block>
    </scroll-view>
    <swiper class="tab-content" current="{{currentTab}}" duration="300" bindchange="switchTab" easing-function="easeOutCubic" style="height:{{swiper_height}};">
      <swiper-item wx:for="{{thList}}">
        <view id="start{{index}}" class='start-view'></view>
        <view wx:if="{{item.contents.length>0}}">
          <block wx:for="{{item.contents}}" wx:key="*this" wx:for-item="swiperItem" wx:for-index="swiperIndex">
            <view wx:if="{{swiperItem.content_type=='ARTICLE'||swiperItem.content_type=='VIDEO'||swiperItem.content_type=='AUDIO'}}" catchtap="todetail" data-swiperItem="{{swiperItem}}">
              <view class="item-ans">
                <view class="avatar">
                  <image class="ans-icon" src="../../../img/label_hot_2@3x.png" wx:if="{{swiperItem.content_identify==='热'}}" />
                  <image class="ans-icon" src="../../../img/label_new_2@2x.png" wx:if="{{swiperItem.content_identify==='新'}}" />
                  <image class="img" src="{{swiperItem.cover}}"></image>
                </view>
                <view class="expertInfo">{{swiperItem.title}}</view>
                <!-- <navigator url="/pages/askExpert/expertDetail" class="askBtn">问TA</navigator> -->
              </view>
            </view>
            <!-- 百科 -->
            <view wx:elif="{{swiperItem.content_type=='WIKI'}}" catchtap="todetail" data-swiperItem="{{swiperItem}}">
              <view class="item-sna">
                <view>
                  <image class="sna-icon" src="../../../img/label_new@2x.png" wx:if="{{swiperItem.content_identify==='新'}}"></image>
                  <image class="sna-icon" src="../../../img/label_re@2x.png" wx:if="{{swiperItem.content_identify==='热'}}"></image>
                  <text class="sna-title">{{swiperItem.title}}</text>
                </view>
                <view class="sna-word">{{swiperItem.content}}</view>
              </view>
            </view>
            <view wx:else>
              <view class="item-question " catchtap="todetail" data-swiperItem="{{swiperItem}}">
                <view class="question">
                  <view class="user">
                    <image class="user" src="{{swiperItem.cover}}"></image>
                  </view>
                  <view class="question-title">{{swiperItem.title}}</view>
                  <view class="question-icon">
                    <image class="sna-icon" src="../../../img/label_new@2x.png"></image>
                  </view>
                </view>
                <view class="answer">{{ swiperItem.content}}</view>
              </view>
            </view>
          </block>
        </view>
        <view wx:else>
          <view class="nodata">此条目下暂无内容</view>
        </view>
        <view id="end{{index}}" class='start-view'></view>
      </swiper-item>
    </swiper>
  </view>
</view>

js

import {
  pub
} from '../../../utils/api.js';
const app = getApp()
Component({
  properties: {
    listItem: {
      type: Object,
      value: {},
    }
  },
  data: {

    thList: [],

    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    swiper_height: 0,

    pageXList: [],
    time: 0,
    tabhWidth: 0,

  },

  ready() {

    if (this.data.listItem) {
      this.setData({
        thList: this.data.listItem.labels
      })
      //算自适应高度必须在这个数字之后,否则Swiper-item 循环会报错

      this.autoHeight()
      let qurry = this.createSelectorQuery()
      qurry.selectAll(".tab-item").boundingClientRect().exec((res) => {
        // console.log(res[0])
        let pageXList = []
        for (let item of res[0]) {
          pageXList.push(item)
        }
        this.setData({
          pageXList
        })

      })
      qurry.select(".tab-h").boundingClientRect().exec((res) => {
        if (res[1]) {
          this.setData({
            tabhWidth: res[1].width
          })
        }
      })
    }
  },
  methods: {
    autoHeight() {
      let {
        currentTab
      } = this.data
      let that = this

      this.createSelectorQuery()
        .select('#end' + currentTab)
        .boundingClientRect()

        .select('#start' + currentTab)
        .boundingClientRect()
        .exec((rect) => {
          let _space = rect[0].top - rect[1].top

          _space = _space + 'px'

          that.setData({
            swiper_height: _space,
          })
        })
    },

    // 点击标题切换当前页时改变样式
    swichNav: function (e) {
      var cur = e.target.dataset.current
      let item = e.target.dataset.item
      if (this.data.currentTaB == cur) {
        return false
      } else {
        this.setData({
          currentTab: cur,
        })
        app.sensors.track('secondPageButtonClick', {
          button_name: "内容栏目-标签-切换",
          column_name: this.data.listItem.column_name,
          tab_name: item.label_name,
        });
        this.autoHeight()
      }
    },
    toAll(e) {
      let id = e.currentTarget.dataset.id
      let url = `/pages/guide/articleColumn?columnId=${id}`
      wx.navigateTo({
        url,
      })
      app.sensors.track('secondPageButtonClick', {
        button_name: "内容栏目-查看全部按钮",
        button_to_url: url
      });
    },
    //判断当前滚动超过一屏时,设置tab标题滚动条。
    checkCor: function () {
      if (this.data.currentTab === 0) {
        this.setData({
          scrollLeft: 0
        })
      } else {
        let left = 0
        // if (this.data.pageXList[this.data.currentTab].right > this.data.tabhWidth * 0.5) {
        //   left = this.data.pageXList[this.data.currentTab].left - 20
        // }
        // this.setData({
        //   scrollLeft: left
        // })

        // var self = this;
        // if (this.data.pageXList[this.data.currentTab].right > this.data.tabhWidth * 0.5) {
        //   const query = this.createSelectorQuery()
        //   query.selectAll('.tab-item').boundingClientRect();
        //   query.exec(function (res) {
        //     //遍历你当前的tab栏 之前的所有dom节点的宽 相加设置为滚动条滚去的scrollLeft 就搞定了
        //     var num = 0;
        //     console.log(res[0], "res[0]");

        //     for (var i = 0; i < self.data.currentTab; i++) {
        //       num += res[0][i].width
        //     }
        //     self.setData({
        //       scrollLeft: Math.ceil(num)
        //     })
        //   })

        // }

        var self = this;
        if (self.data.currentTab >= 2) {
          const query = this.createSelectorQuery()
          query.selectAll('.tab-item').boundingClientRect();
          query.exec(function (res) {
            let scrollLeft = 0
            res[0].forEach((itm, idx) => {
              if (idx <= self.data.currentTab - 2) {
                scrollLeft += (itm.width)
              }
            })
            self.setData({
              scrollLeft: scrollLeft
            })

          })

        }
        // this.setData({
        //   scrollLeft: left
        // })
        // let num = 0
        // let qurry = this.createSelectorQuery()
        // qurry.selectAll(".tab-item").boundingClientRect().exec((res) => {
        //   let clicknum = this.data.currentTab
        //   console.log(res[0], "aaa");
        //   let list = res[0]
        //   for (let i = 0; i < list.length; i++) {
        //     if (list[i].right > this.data.tabhWidth * 0.6) {
        //       num = i
        //       console.log(num);
        //       break;
        //     }
        //   }
        //   left = list[num].left
        //   left += Math.floor(this.data.pageXList[this.data.currentTab].left / this.data.tabhWidth) * this.data.tabhWidth
        //   if (this.data.currentTab >= num) {
        //     console.log(left, "455454");
        //     this.setData({
        //       scrollLeft: left
        //     })
        //   }
        // })
      }
    },

    switchTab: function (e) {
      this.setData({
        currentTab: e.detail.current,
      })

      this.autoHeight()
      this.checkCor()
    },

    todetail: function (e) {
      // console.log(e);
      let time = +new Date()
      if (time - this.data.t < 1000) return
      this.setData({
        t: time
      })
      let swiperitem = e.currentTarget.dataset.swiperitem
      let type = e.currentTarget.dataset.swiperitem.content_type
      let id = e.currentTarget.dataset.swiperitem.refer_id

      let url = ''
      if (type === 'ARTICLE') { //文章
        url = `/pages/article/article?id=${id}`;
      } else if (type === 'AUDIO') { //音频
        let AudioStatus = JSON.parse(wx.getStorageSync("AudioStatus") || "{}")
        let AudioStatusId = AudioStatus[id] || {}
        let progress = pub.TimetoNum(AudioStatusId.progress || "00:00");

        let obj = {
          id: id,
          time: swiperitem.audioTime,
          title: swiperitem.title,
          selectid: swiperitem.typeId,
          path: swiperitem.audioUrl,
          loding: false,
          startTime: progress,
          cover_url: swiperitem.cover,
        }

        url = `/pages/audio/details?data=${JSON.stringify(obj)}`;
      } else if (type === 'WIKI') { //百科
        url = `/pages/encyclopedia/detail?id=${id}&title=${swiperitem.title}`
      } else if (type === 'QUESTION') { //问答
        url = `/pages/answer/details?id=${id}`;
      } else { //视频
        url = `/pages/video/index?id=${id}&title=${swiperitem.title}&type=${swiperitem.type}`
      }
      wx.navigateTo({
        url,
      })
      app.sensors.track('secondPageButtonClick', {
        button_name: "内容栏目-标签-点击",
        column_name: this.data.listItem.column_name,
        tab_name: this.data.listItem.labels[this.data.currentTab].label_name,
        button_to_url: url
      });
    }
  },
})

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!