13

解决Taro下RichText遇到的图片宽度问题

 4 years ago
source link: https://zackzheng.info/2019/08/27/resolve-image-width-in-richtext/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

解决Taro下RichText遇到的图片宽度问题

2019-08-27

| Tech

| 18

解决Taro下RichText遇到的图片宽度问题

使用TaroRichText组件,遇到展示图片的宽度超出屏幕的问题,记录下解决办法。可以根据实际需要,对以下方法进行修改。

  • 只有图片标签,并且图片标签没有设置style和宽度/高度
1
2
3
4
function formatRichText(html){
let newContent= html.replace(/\<img/gi, '<img style="width:100%;height:auto"');
return newContent;
}
  • 包含多种标签
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 处理富文本里的图片宽度自适应
* 1.去掉img标签里的style、width、height属性
* 2.img标签添加style属性:max-width:100%;height:auto
* 3.修改所有style里的width属性为max-width:100%
* 4.去掉<br/>标签
* @param html
* @returns {void|string|*}
*/
function 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:block;margin-top:0;margin-bottom:0;"');
return newContent;
}

-END-
欢迎到我的博客交流:https://zackzheng.info


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK