微信小程序工具函数库(持续更新)
整理一些微信小程序专属的工具函数,由于机型和版本库的不同,小程序还是有很多兼容问题的,这里的部分函数针对兼容性统一进行了封装,可以直接拿来在项目中使用,此文章会持续更新。
// 基础库的版本号比较
const compareVersion = (v1, v2) => {
v1 = v1.split('.')
v2 = v2.split('.')
const len = Math.max(v1.length, v2.length)
while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}
for (let i = 0; i < len; i++) {
const num1 = parseInt(v1[i])
const num2 = parseInt(v2[i])
if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
// 小程序系统顶部数据
const getHeaderData = () => {
let systemInfo = wx.getSystemInfoSync(),//系统信息
statusBarHeight = systemInfo.statusBarHeight, //状态栏高度
headMenuCoordinates = null, //右上角胶囊坐标
headMenuPosition = null, //右上角胶囊绝对定位
navbarHeight = null, //导航栏高度
headerHeight = null //整个顶部高度
if (compareVersion(systemInfo.SDKVersion, '2.1.0') >= 0 || wx.getMenuButtonBoundingClientRect) {
// 胶囊坐标位置,基于屏幕左上角
headMenuCoordinates = wx.getMenuButtonBoundingClientRect()
// 转换后的胶囊绝对位置
headMenuPosition = {
width: headMenuCoordinates.width,
height: headMenuCoordinates.height,
// 胶囊top - 状态栏高度
top: headMenuCoordinates.top - statusBarHeight,
// 胶囊bottom - 胶囊height - 状态栏height (现胶囊bottom 为距离导航栏底部的长度)
bottom: headMenuCoordinates.bottom - headMenuCoordinates.height - statusBarHeight,
// 屏幕宽度 - 胶囊right
right: systemInfo.screenWidth - headMenuCoordinates.right
}
// 导航栏高度 原胶囊bottom + 现胶囊bottom
navbarHeight = headMenuCoordinates.bottom + headMenuPosition.bottom
} else {
let { model } = systemInfo
if (model.includes('iPhone') && model.includes('X')) {
// iphone X系列
navbarHeight = 88
} else if (model.includes('iPhone')) {
// iphone 6系列
navbarHeight = 64
} else {
// android
navbarHeight = 68
}
}
// 整个顶部高度 状态栏高度 + 导航栏高度
headerHeight = statusBarHeight + navbarHeight
return {
systemInfo,
statusBarHeight,
headMenuCoordinates,
headMenuPosition,
navbarHeight,
headerHeight,
}
}
一起加油!老铁们
加我🐧1621997803,一起学习、交流。
厉害了
用不了我的昵称了吧🤭
老哥前后端一个人弄的?
是的
呵呵
啊,不要用我的昵称😟
来看看
你是我的小呀小苹果
来了老弟
大神,求带飞
aoligei
干就完了,奥力给