微信小程序scroll-view滑动点击跟随导航

微信小程序scroll-view滑动点击跟随导航:

<view class="demo">
    <!-- 导航 -->
    <view class="nav-list">
        <scroll-view scroll-x="{{true}}" scroll-with-animation="true" class="nav-scroll-view" scroll-left="{{scrollLeft}}" show-scrollbar="{{false}}">
            <view class="row">
                <view class="nav-item {{index == viewNavIndex && 'active'}}" wx:for="{{10}}" wx:key="index" bindtap="handleClickNav" data-nav="{{index}}">
                    列表{{index + 1}}
                </view>
            </view>
        </scroll-view>
    </view>
    <!-- 内容 -->
    <view class="list-wrapper">
        <scroll-view class="list-container" id="list-container" bindscroll="handleListScroll" bind:touchstart="handleTouchScrollView" scroll-x="{{true}}" scroll-into-view="scroll-item-{{clickedNavIndex}}" show-scrollbar="{{false}}" scroll-with-animation="{{true}}">
            <view class="content">
                <view class="list" wx:for="{{10}}" wx:key="index" id="scroll-item-{{index}}" style="background-color:{{colorString[index]}}">
                    <text class="list-item">{{item}}</text>
                </view>
            </view>
        </scroll-view>
    </view>
</view>
/* 防抖 */
function debounce(fn, interval) {
  let timer;
  let delay = interval || 500;
  return function () {
    let that = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      fn.apply(that, args);
    }, delay);
  };
}
// pages/demo/demo.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isTouchScrollView: false, // 锁定
    clickedNavIndex: 0, // 点击index
    viewNavIndex: 0, // 锚点
    nodeInfoList: [], // 节点信息
    leftDistance: 0,
    scrollLeft: 0, // 左偏移
    contentScrollW: 0, // 导航总宽度
    nodeNavList: [], // 节点信息
    colorString: [], // 随机颜色(非必要)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData();
  },
  // 随机颜色
  getData() {
    var { row, colorString } = this.data;
    var ColorCharacter = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
    ];

    for (var i = 0; i < 10; i++) {
      var HomeNumber = "#";

      for (var j = 0; j < 6; j++) {
        var NumberRand = Math.floor(Math.random() * 16);
        HomeNumber += ColorCharacter[NumberRand];
      }
      colorString.push(HomeNumber); // 追加到colorString末尾
    }
    console.log(colorString);

    this.setData({
      colorString,
    });
  },

  // 初始化节点
  initNode() {
    const that = this;
    const query = wx.createSelectorQuery().in(this);
    query
      .select(".nav-scroll-view")
      .boundingClientRect((data) => {
        console.log(data);
        // 拿到 scroll-view 组件宽度
        this.data.contentScrollW = data.width;
      })
      .exec();
    query
      .selectAll(".nav-item")
      .boundingClientRect((data) => {
        console.log(data);
        that.setData({
          nodeNavList: data,
        });
      })
      .exec();
    query
      .selectAll("#list-container .list")
      .boundingClientRect((data) => {
        console.log(data);
        that.setData({
          nodeInfoList: data,
        });
      })
      .exec();
  },
  // nav 点击
  handleClickNav(e) {
    const that = this;
    const { nav } = e.currentTarget.dataset;
    console.log(nav);
    const { isTouchScrollView, clickedNavIndex } = this.data;
    if (!isTouchScrollView && clickedNavIndex == nav) return;
    // 锁定联动
    this.data.isTouchScrollView = false;
    // 解决clickedNavIndex相同触发更新失败
    if (clickedNavIndex == nav) {
      return;
      this.setData({
        clickedNavIndex: -1,
      });
    }
    wx.nextTick(() => {
      that.setData({
        clickedNavIndex: nav,
        viewNavIndex: nav,
        scrollLeft: that.getScrollLeft(nav),
      });
    });
  },
  // 滑动
  handleListScroll(e) {
    // console.log("e: ", e);
    const { isTouchScrollView, nodeInfoList, leftDistance } = this.data;
    if (!isTouchScrollView) return;
    this.scrollLeft = e.detail.scrollLeft;
    // console.log("scrollLeft: " + this.scrollLeft);
    let currentNavIndex = nodeInfoList
      .map((item, index) => ({ index, ...item }))
      .filter((item) => item.left <= this.scrollLeft + leftDistance)
      .sort((a, b) => b.left - a.left)[0].index;
    this.setData({
      viewNavIndex: currentNavIndex,
      scrollLeft: this.getScrollLeft(currentNavIndex),
    });
  },
  // 获取导航偏移
  getScrollLeft(index) {
    const { nodeNavList, contentScrollW } = this.data;
    const scrollLeft =
      nodeNavList[index].left -
      contentScrollW / 2 +
      nodeNavList[index].width / 2;
    return scrollLeft;
  },

  handleTouchScrollView() {
    this.data.isTouchScrollView = true;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.initNode();
  },

});

.demo {
  .nav-list {
    display: flex;
    position: sticky;
    top: 0;
    left: 0;
    z-index: 9;
    width: 100%;
    background-color: #fff;
    .row {
      display: flex;
    }
    .nav-item {
      padding: 25rpx 15rpx;
      font-size: 28rpx;
      text-align: center;
      white-space: nowrap;
      transition: transform 0.1s linear;
      &.active {
        color: #fb7d34;
        transform-origin: center center;
        transform: scale(1.1);
      }
      &:active {
        background-color: rgba(0, 0, 0, 0.1);
      }
    }
  }
  .list-wrapper {
    width: 100%;
    position: relative;
    .list-container {
      display: flex;
      width: 100%;
      .content {
        display: flex;
      }
      .list {
        flex: 0 0 750rpx;
        height: 300rpx;
      }
    }
  }
  ::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
  }
}

效果图

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
微信小程序中,scroll-view 组件默认会阻止页面上其他元素的滑动事件,这可以通过设置 `catchtouchmove` 属性来解决。 具体做法如下: 1. 在 scroll-view 组件上添加 `catchtouchmove="true"` 属性,如下所示: ```html <scroll-view catchtouchmove="true"> <!-- scroll-view 内容 --> </scroll-view> ``` 2. 在页面的 `onLoad` 或 `onReady` 生命周期中,获取 scroll-view 组件的高度和宽度,然后在页面上添加一个与 scroll-view 同样大小的透明的 view,并将其 zIndex 设置为比 scroll-view 更高的数值,这样就可以让页面上的其他元素在透明的 view 上进行滑动了。代码如下: ```javascript onLoad: function () { var that = this; wx.createSelectorQuery().select('#scrollview').boundingClientRect(function (rect) { that.setData({ scrollHeight: rect.height }); }).exec(); wx.getSystemInfo({ success: function (res) { that.setData({ windowHeight: res.windowHeight }); } }); }, ``` ```html <!-- 添加一个与 scroll-view 大小相同的透明 view --> <view class="transparent-view" style="height: {{windowHeight - scrollHeight}}px; z-index: 1;"></view> <scroll-view id="scrollview" catchtouchmove="true"> <!-- scroll-view 内容 --> </scroll-view> ``` 3. 在页面的 CSS 中,让透明的 view 不显示出来,代码如下: ```css .transparent-view { background-color: transparent; } ``` 通过以上步骤,就可以解决微信小程序scroll-view 组件滑动穿透的问题了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值