实现原理及思路
-
SelectorQuery
NodesRef.boundingClientRect(function callback)
进入微信官方文档查看 -
示例代码
Page({
getRect () {
wx.createSelectorQuery().select('#the-id').boundingClientRect(function(rect){
rect.id // 节点的ID
rect.dataset // 节点的dataset
rect.left // 节点的左边界坐标
rect.right // 节点的右边界坐标
rect.top // 节点的上边界坐标
rect.bottom // 节点的下边界坐标
rect.width // 节点的宽度
rect.height // 节点的高度
}).exec()
},
getAllRects () {
wx.createSelectorQuery().selectAll('.a-class').boundingClientRect(function(rects){
rects.forEach(function(rect){
rect.id // 节点的ID
rect.dataset // 节点的dataset
rect.left // 节点的左边界坐标
rect.right // 节点的右边界坐标
rect.top // 节点的上边界坐标
rect.bottom // 节点的下边界坐标
rect.width // 节点的宽度
rect.height // 节点的高度
})
}).exec()
}
})
- 在控制台输出内容
onLoad: function (options) {
const _this = this
wx.createSelectorQuery().select('#img').boundingClientRect(function (res) {
console.log(res)
}).exec();
}
<view id="img"></view>
- 注意
有时会出现输出值为null
的情况,可能是因为你添加了wx:if或者wx:for
如果是wx:for元素是根据循环渲染的。使用节点获取信息需要在你获取数据接口之后完成渲染才不会返回空的。如果是wx:if的话,值为true
才可以获取到值。
代码实现
imageScale.wxml
<!--pages/imageScale/imageScale.wxml-->
<view class="container">
<view>请点击空白处选择图片(当前比例4:3)</view>
<view class="upload" id="img" style="height:{{height}}" bindtap="chooseImage">
<image src="{{src}}" alt=""></image>
</view>
</view>
app.wxss
/**app.wxss**/
.container {
height: 100vh;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: flex-start;
box-sizing: border-box;
background: #eee;
padding: 20rpx;
}
imageScale.wxss
/* pages/imageScale/imageScale.wxss */
.upload{
width: 100%;
background: #fff;
}
image{
width: 100%;
height: 100%;
}
imageScale.js
// pages/imageScale/imageScale.js
Page({
/**
* 页面的初始数据
*/
data: {
height: '',
src: ''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const _this = this
wx.createSelectorQuery().select('#img').boundingClientRect(function (res) {
console.log(res)
_this.setData({
height: res.width * 0.75 + 'px'
})
}).exec();
},
//选择图片
chooseImage() {
const _this = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths
_this.setData({
src: tempFilePaths[0]
})
}
})
},
})