zoukankan      html  css  js  c++  java
  • Live2d Test Env

    在看本篇以前,期待读者先了解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)

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

    以上。

     

    
    
  • 相关阅读:
    Java:多线程
    javascript:正则表达式、一个表单验证的例子
    DOM对象和window对象
    javascript:面向对象和常见内置对象及操作
    如何检查CentOS服务器受到DDOS攻击
    CentOS防SYN攻击
    CentOS服务器简单判断CC攻击的命令
    在VMware中为CentOS配置静态ip并可访问网络
    安全运维之:网络实时流量监测工具iftop
    安全运维之:网络实时流量监测工具iftop
  • 原文地址:https://www.cnblogs.com/hjk1124/p/12174778.html
Copyright © 2011-2022 走看看