微信小程序 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(/style="[^"]+"/gi, '').replace(/style='[^']+'/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(/style="[^"]+"/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 style="max-width:100%;height:auto;display:block;margin:10px 0;"');
23   return newContent;
24 }
25 
26 
27 // 模塊出口
28 module.exports = {
29   formatRichText,
30 };

轉載於:https://www.cnblogs.com/lovelh/p/12747497.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM