luvhl 2020-01-10
在看本篇以前,期待读者先了解js的document.querySelector 方法,在此不做赘述。
由于微信官方禁止小程序操作dom元素,因而无法像前端一样操作小程序DOM,好在官方提供了API ,
这个api叫做 wx.createSelectorQuery(), 官方定义:返回一个 SelectorQuery 对象实例。
这个api的<span>select()方法用于查找元素,类似jq的元素选择器<span><br /></span></span>
尔后有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)如果有哪些错误,欢迎指教
以上。
Vue和React是数据驱动视图,如何有效控制DOM操作?能不能把计算,更多的转移为js计算?因为js执行速度很快。patch函数-->patch,对比tag,对比tag与key,对比children