场景:

  在很多情况下,一个订单类项目需要加载很多数据,但是这时候项目的标题会跟着滚动走,不利于查看对应的项目

解决:

  这时候可以使用 scroll-view 来处理需要滚动的项目内容。

代码如下:

view

<view class="tablebox">
  <view class="tr">
    <view class="th">时间</view>
    <view class="th">账号</view>
  </view>
  <view class="scrollView" id="scrollView" style="position: absolute;bottom: 0;width: 100%;top:92rpx">
    <scroll-view scroll-y>
      <view class="tr" wx:for="{{scrollData}}">
        <view class="td">{{item.time}}</view>
        <view class="td">{{item.phone}}</view>
      </view>
    </scroll-view>
  </view>
</view>

wxss

.tablebox {
  background: #eee
}

.tablebox .tr {
  margin-bottom: 2rpx;
  display: flex
}

.tablebox .tr .th {
  flex: 1;
  height: 90rpx;
  font-size: 32rpx;
  padding: 0 15rpx;
  overflow: hidden;
  box-sizing: border-box;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  color: #333
}

.tablebox .tr .td {
  flex: 1;
  height: 80rpx;
  padding: 0 5rpx;
  overflow: hidden;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  background: #fff;
  color: #333
}

.tablebox .tr:last-child .td {
  border-bottom: 0
}

.scrollView {
  background: #eee
}

.scrollView scroll-view {
  width: 100%;
  height: 100%
}

这样就能让th定格在页面上,scroll-view为绝对定位在页面上,td的内容元素在scroll-view中滚动



这时候问题来了,因为每部手机的像素点不一致,手写scroll-view的absolute top并不靠谱。

如何解决这个问题呢,实际上微信里面有获取当前元素距顶部的数值的API

wx.createSelectorQuery()

我们只需要调用这个API,并动态修改top值就行了

我们可以定义一个函数来处理,console.log(rect)中就有我们需要的参数

getTop: function() {
  var that = this
  wx.createSelectorQuery().select('#scrollView').boundingClientRect(function(rect) {
    console.log(rect)
  }).exec()
}


在onLoad时调用这个函数,并把值绑定到view层

view

<view class="tablebox">
  <view class="tr">
    <view class="th">时间</view>
    <view class="th">账号</view>
  </view>
  <view class="scrollView" id="scrollView" style="{{style}}">
    <scroll-view scroll-y>
      <view class="tr" wx:for="{{scrollData}}">
        <view class="td">{{item.time}}</view>
        <view class="td">{{item.phone}}</view>
      </view>
    </scroll-view>
  </view>
</view>

js

onLoad: function() {
    var that = this
    that.getTop('scrollView')
},
getTop: function(id) {
  var that = this
  wx.createSelectorQuery().select(id).boundingClientRect(function(rect) {
    that.setData({
      style: 'position: absolute;bottom: 0;width: 100%;top:' + rect.top + 'px'
    })
  }).exec()
}






这时候就不用害怕因为手机不同,会出现样式问题了




版权声明:本文为blankshsh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/blankshsh/article/details/78115011