需求:在做小程序头部也就是导航栏和状态栏fixed定位,内容栏要获取到top值,也就是状态栏高度+导航栏高度44px,(因为我的需求中还有一个banner,而设计稿给到的是rpx,状态栏和导航栏则是px,需要统一,因此涉及到单位转换)
//px转为rpx
pxToRpx(px) {
const screenWidth = uni.getSystemInfoSync().screenWidth //窗口宽度
const statusHeight = uni.getSystemInfoSync().statusBarHeight //状态栏
//val就是状态栏高度+导航栏高度(px为传入的导航栏的高度) 此时单位是px
const val = px + statusHeight
this.headHeight = (750 * Number.parseInt(val)) / screenWidth //转换单位为rpx
return this.headHeight
},
//获取不同banner下的top高度
getHeight() {
this.pxToRpx(44)
//这里是按需加减 我这三个分别是不同的banner
this.headH = this.headHeight + 75 + 34 + 'rpx'
this.bannerH1 = this.headHeight + 271 + 75 + 34 + 'rpx'
this.bannerH2 = this.headHeight + 231 + 75 + 34 + 'rpx'
},
还有rpx转px 逻辑一样,一般来说不用特意转px,最后解析都会自动解析为px,这里个方法一般也是因为不同单位之间需要计算时使用
//rpx转为px 传参类型是数字(Number)
rpxTopx(rpx) {
const screenWidth = uni.getSystemInfoSync().screenWidth //窗口宽度
let px = (screenWidth / 750) * Number.parseInt(rpx) //转换单位为px
return Math.floor(px)
}
//px转rpx 传参类型是数字(Number)
pxToRpx(px) {
const screenWidth = uni.getSystemInfoSync().screenWidth //窗口宽度
let rpx = (750 * Number.parseInt(px)) / screenWidth //转换单位为rpx
return Math.floor(rpx)
}