在微信小程序开发中,使用 rich-text
富文本标签经常碰到图片超出屏幕宽度,空白换行不起作用的问题,解决思路是使佣正则匹配对应的标签,增加默认的样式,代码如下
/**
* 追加节点行内样式
* @param {String} html 富文本字符串
* @param {String} nodeName 匹配节点的名称
* @param {String} style 追加的行内样式
* @returns {String}
*/
const appendNodeLineStyle = (html, nodeName, style) => {
const reg = new RegExp(`<${nodeName}.*?>`, 'ig')
return html.replace(reg, match => {
// 检测是否有 `style` 属性
if (match.indexOf('style=') !== -1) {
// 在原有的 `style` 属性后面加上新的行内样式
return match.replace(/style="(.*?)"/, `style="${style}$1"`);
} else {
// 否则直接添加 `style` 属性和行内样式属性
return match.replace(/<img/, `<img style="${style}"`);
}
})
}
/**
* 格式化富文本内容
* @param {string } html
* @returns {string}
*/
const formatRichText = (html) => {
if (typeof html !== 'string') {
html = ''
}
// 解决图片宽度不能自适应的问题
html = appendNodeLineStyle(html, 'img', 'max-width:100%;height:auto;')
// 解决 `p` 标签在后台有默认的上下外边距,到小程序里没有上下外边距的问题
html = appendNodeLineStyle(html, 'p', 'margin-block-start:1em;margin-block-end:1em;')
// 解决微信小程序会忽略空白换行的问题
html = html.replace(/ /g, '\u00A0')
return html
}
接着调用上面的方法,即可处理好替换后的 html
字符串,示例如下:
// 例如 `data` 是后端返回的接口数据
const data = {
id: 1,
// 富文本字符串
rich: ''
}
this.setData({
detail: {
...data,
rich: formatRichText(data.rich)
}
})
<rich-text nodes="{{detail.rich}}"></rich-text>
以上代码也只是处理一些简单的富文本问题,想要让富文本有更多功能,如:点击图片可以预览、图片懒加载等,需要使用一些第三方插件,推荐一个好用富文本插件