微信小程序横向滚动,选中的部分保持在中间

js部分

//写在page外
var screenWidth = wx.getSystemInfoSync().windowWidth;
let itemWidth = screenWidth / 5;//表示窗口横排显示5个item
//点击item时调用scrollLeft方法
scrollLeft() {
    let tabList = this.data.tabList
    let tabIndex = this.data.tabIndex
    let scrollX = itemWidth * tabIndex - itemWidth * 2;
    let maxScrollX = (tabList.length + 1) * itemWidth;
    if (scrollX < 0) {
      scrollX = 0;
    } else if (scrollX >= maxScrollX) {
      scrollX = maxScrollX;
    }
    this.setData({
      x: scrollX
    })
  },
//item部分用scroll-view标签
<scroll-view scroll-x scroll-left="{{x}}" scroll-with-animation="true" class="punchCardDoExam_box_tab flex-j-start">
	<view class="perfectCourse_tab_box flex-j-start">
		<block wx:for="{{tabList}}" wx:key="index">
			<view class="perfectCourse_tab_box_item flex {{tabIndex==index?'curTabBg':''}}" data-index="{{index}}" data-type="{{item.bookType}}" bindtap="chooseTab">
				{{item.name}}
			</view>
		</block>
	</view>
</scroll-view>

还可以在内容的部分加上触摸滑屏的功能

<view bind:touchstart="touchStart" bind:touchmove="touchMove" bind:touchend="touchEnd">
//内容部分
</view>
var startX, endX;
var moveFlag = true; // 判断执行滑动事件

记得在move() 方法里调用 scrollLeft(),内容部分滑动的时候,上方的横向tab相应的item也会在正中间

// 触屏滑动
  move(type) {
    if (type == 1) {
      if (this.data.tabIndex > 0) {
        let tabIndex = this.data.tabIndex;
        tabIndex--;
        this.setData({
          tabIndex: tabIndex
        })
      }
    } else {
      if (this.data.tabIndex < this.data.tabList.length - 1) {
        let tabIndex = this.data.tabIndex;
        tabIndex++;
        this.setData({
          tabIndex: tabIndex
        })
      }
    }
    this.scrollLeft();
  },
  touchStart: function (e) {
    startX = e.touches[0].pageX; // 获取触摸时的原点
    moveFlag = true;
  },
  // 触摸移动事件
  touchMove: function (e) {
    endX = e.touches[0].pageX; // 获取触摸时的原点
    if (moveFlag) {
      if (endX - startX > 50) {
        this.move(1);
        moveFlag = false;
      }
      if (startX - endX > 50) {
        this.move(2);
        moveFlag = false;
      }
    }
  },
  // 触摸结束事件
  touchEnd: function (e) {
    moveFlag = true; // 回复滑动事件
  },
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值