微信小程序实时监听某个元素高度

微信开放文档:https://developers.weixin.qq.com/miniprogram/dev/api/wxml/wx.createSelectorQuery.html

wx.createSelectorQuery().select('#curr').boundingClientRect(function(rect){
      rect.id      // 节点的ID
      rect.dataset // 节点的dataset
      rect.left    // 节点的左边界坐标
      rect.right   // 节点的右边界坐标
      rect.top     // 节点的上边界坐标
      rect.bottom  // 节点的下边界坐标
      rect.width   // 节点的宽度
      rect.height  // 节点的高度
}).exec()

效果图如下所示

在这里插入图片描述

.wxml

<image src="http://attachments.gfan.com/forum/attachments2/day_110317/1103171814794ace68f8b856a8.jpg" wx:for="{{2}}" wx:key="index"></image>
<view id="curr">
  <view style="{{curr?'position:fixed;top:0;':''}}">
    监听内容
  </view>
</view>
<image src="http://hiphotos.baidu.com/784514578845415478/pic/item/43f581dd064f0c2e485403f8.jpg" wx:for="{{3}}" wx:key="index"></image>

.wxss

image{
  width: 100%;
}
view{
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  background-color: #f7f7f7;
}

.js

Page({
  data: {
    cure: false
  },
  onPageScroll: function (e) {
    let that = this;
    wx.createSelectorQuery().select('#curr').boundingClientRect(function (rect) {
      if(0 <= rect.top){
        that.setData({
          curr:false
        })
      }else{
        that.setData({
          curr:true
        })
      }
    }).exec()
  },
})

利用wx.createSelectorQuery来获取某个元素的属性来完成一系列操作,我这里主要是获取高度对某个元素进行定位。


有什么问题欢迎评论留言,我会及时回复你的

原创文章 75 获赞 87 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43764578/article/details/105706732