首页 > 微信 > 详细

关于获取小程序组件的dom元素属性(详尽版)

时间:2020-01-10 11:14:40      阅读:864      评论:0      收藏:0      [点我收藏+]

在看本篇以前,期待读者先了解js的document.querySelector 方法,在此不做赘述。

由于微信官方禁止小程序操作dom元素,因而无法像前端一样操作小程序DOM,好在官方提供了API ,

这个api叫做 wx.createSelectorQuery(),  官方定义:返回一个 SelectorQuery 对象实例。

这个api的select()方法用于查找元素,类似jq的元素选择器

尔后有boundingClientRect(function(res){})则返回指定元素的DOM属性,res代表元素本身,(百度了boundingClientRect :边界中心)

再之后的exec(function(rect){})则是设置元素属性,rect在这里指的是所有匹配到结果的集合,通过调用that/this.setdata({})可以更改元素dom值,请注意!rect是一个数组集合,想要设置某一个元素,需要给该数组加指定元素的下标!

来个简单demo:

wxml:

 <swiper current="{{currentData}}" class=‘swiper‘ style="height:{{swiperHeight}}px;" duration="300" bindchange="bindchange">
    <swiper-item>

      <view class="cont1">111</view>
       
    </swiper-item>

在这个demo里 我想获取.cont1的高度从而动态调整swiper的高度,因而我给swiper的高度设置了参数swiperHeight

wx.js:

page({
    data:{
         swiperHeight:0    
    } ,
     /*由于期待页面加载完毕就显示,所以我放在了onload函数内*/
     /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this
    const query = wx.createSelectorQuery();
    query.select(‘.cont1‘).boundingClientRect(function (res) {
//这里返回元素自身的DOM属性
          console.log(res);

    }).exec(function(rect){
        that.setData({
          swiperHeight: rect[0].height + 0
        })
        // rect返回一个数组,需要使用下标0才能找到
        // console.log(s[0].height)
    });

  },
    



})
        

 

网上听大佬说偶尔会有rect返回为null的意外,昨晚翻遍百度,终于找到了一个解决方法,感谢那位大佬(传送门)

    /*原理是使用定时器异步获取dom*/
    setTimeout(function () { var query = wx.createSelectorQuery(); query.select(‘.cont1‘).boundingClientRect(); query.exec(function (rect) { if (rect === null) return; that.setData({ swiperHeight: rect .height + 10 }) }); }, 500)

如果有哪些错误,欢迎指教

以上。

 

 

 

关于获取小程序组件的dom元素属性(详尽版)

原文:https://www.cnblogs.com/hjk1124/p/12174778.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!