微信小程序富文本内容中的图片处理
后台上传图片,大小各异,为了让图片在微信小程序更好的的显示,进行了以下处理:
找到内容中的图片,去除原有的宽高属性,给图片加上的宽度最大100%,高度自适应的样式
formatRichTextImg = (html) => {
let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
match = match.replace(/style="[^"]+"/gi, '').replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
return newContent;
}
参考:https://blog.csdn.net/weixin_55556204/article/details/124488693

浙公网安备 33010602011771号