【微信小程序】【Demo】获取页面元素宽高,按相对百分比计算页面其他元素应设置宽度的像素数值。
/** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { var that = this; //获取元素 var query = wx.createSelectorQuery(); query.select("#navbar").boundingClientRect((rect) => { var wW = wx.getSystemInfoSync().windowWidth; var wH = wx.getSystemInfoSync().windowHeight; //原始主体宽高 var oldW = 551; var oldH = 694; //显示宽 var bgW = wW * 0.8; //主体元素宽高比例,则高为 var bgH = bgW * oldH / oldW ; var bgLeft = wW * 0.1; var bgTop = (wH-bgH)/2; //券和按钮占高度 var btnH =bgH * 130/oldH; var ruleH =bgH * 50/oldH; that.setData({ bgStyle:"width:"+bgW+"px;"+"height:"+bgH+"px;"+"top:"+bgTop+"px;"+"left:"+bgLeft+"px;", bgTop: bgTop, bgLeft: bgLeft, btnH:btnH, ruleH:ruleH, }) }).exec(); },