⼩程序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|*}
html富文本框9*/
10function formatRichText(html){
11  let newContent= place(/<img[^>]*>/gi,function(match,capture){
12      match = place(/]+"/gi, '').replace(/style='[^']+'/gi, '');
13      match = place(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
14      match = place(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
15return match;
16  });
17  newContent = place(/]+"/gi,function(match,capture){
18      match = place(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
19return match;
20  });
21  newContent = place(/<br[^>]*\/>/gi, '');
22  newContent = place(/\<img/gi, '<img ');
23return newContent;
24 }
25
26
27// 模块出⼝
ports = {
29  formatRichText,
30 };