微信小程序 rich-text 富文本中图片自适应

如果文本中的图片只有<img src="">那么可以直接替换,但是如果有其他的样式比如width,height,style时就需要先去掉其,再替换

方法如下:

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

转载于:https://www.cnblogs.com/lovelh/p/12747497.html