解决富文本图片错乱问题
225字小于1分钟
2025-03-29
在使用 uniapp
自带的 rich-text
组件时,发现图片显示不正常,图片显示为空,或者显示为乱码。
解决方案:
使用过滤器对富文本内容进行过滤,控制图片大小,并添加样式。
filters: {
formatRichText(html) {
//控制小程序中图片大小
let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
match = match
.replace(/style="[^"]+"/gi, "")
.replace(/style='[^']+'/gi, "")
match = match
.replace(/width="[^"]+"/gi, "")
.replace(/width='[^']+'/gi, "")
match = match
.replace(/height="[^"]+"/gi, "")
.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:inline-block;margin:10rpx auto;"'
)
return newContent
},
}
- 也可以使用uview框架的富文本组件
uParse
,解决富文本图片显示问题。 - 使用
vueExtend.js
插件,解决富文本图片显示问题。