开发过程中有时候会有些需求,常规的方法并不能解决问题。此文介绍下一些解决方案

小程序

获取头部高度

1
2
3
4
5
6
7
8
9
10
// 获取头部高度
wx.getSystemInfo({
success: e => {
let pixelRatio = 750 / e.windowWidth;
this.globalData.pixelRatio = pixelRatio;
this.globalData.statusBar = e.statusBarHeight;
this.globalData.headerHeight = 44;
this.globalData.customBar = e.statusBarHeight+this.globalData.headerHeight;
}
})

移动端

判断浏览器环境

1
2
3
4
5
6
7
8
9
10
11
12
const ua = navigator.userAgent;
// 微信浏览器
if(ua.toLowerCase().indexOf('micromessenger') > -1){
console.log('微信浏览器')
}

// 安卓、苹果
if(ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1){
console.log('安卓环境')
}else{
console.log('苹果环境')
}

其他

富文本解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 处理富文本里的图片宽度自适应
* 1.去掉img标签里的style、width、height属性
* 2.img标签添加style属性:max-width:100%;height:auto
* 3.修改所有style里的width属性为max-width:100%
* 4.去掉<br/>标签
* @param html
* @returns {void|string|*}
*/
formatRichText(html) {
let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
match = match.replace(/style="[^"]+"/gi, '');
match = match.replace(/width="[^"]+"/gi, '');
match = match.replace(/height="[^"]+"/gi, '');
return match;
})
newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
})
newContent = newContent.replace(/<br[^>]*\/>/gi, '')
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
return newContent;
}