uni-app:解析富文本图片超出

1.如果解析富文本,图片没有设置style和宽度/高度

formatRichText(html){
            let newContent= html.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
            return newContent;
               }

// let newContent= html.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"'); 每个匹配到的<img>标签添加一个style属性,其值为max-width:100%;height:auto;display:block;

调用方法:this.context = this.formatRichText(content)

2.里包含多种标签

(1).去掉img标签里的style、width、height属性;

(2).img标签添加style属性:max-width:100%;height:auto;

(3).修改所有style里的width属性为max-width:100%;

(4)去掉<br/>标签。

formatRichText(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(/style="[^"]+"/gi,function(match,capture){
match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');return match;});
newContent = newContent.replace(/<br[^>]/>/gi, '');
newContent = newContent.replace(/<img/gi, '<img style="width:100%;height:auto;display:block;"');
return newContent;
}

代码注释:

let newContent = html.replace(/<img[^>]>/gi, function(match, capture)  //  这行代码开始处理HTML内容中的所有 <img> 标签。
match = match.replace(/style="[^"]+"/gi, '').replace(/style\s?=\s*?([‘"])[\s\S]?\1/ig, '');  //  移除 <img> 标签中的 style 属性,不管这个属性是用双引号还是单引号包围的。
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');  //  行代码移除 <img> 标签中的 width 属性,不管这个属性是用双引号还是单引号包围的。
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');return match;}); //  这行代码移除 <img> 标签中的 height 属性,不管这个属性是用双引号还是单引号包围的。
return match // 替换函数返回修改后的 match 字符串,即移除了 style、width 和 height 属性的 <img> 标签。
newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture)  // 这行代码开始处理HTML内容中的所有 style 属性。
match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;') // 在这个替换函数中,它查找任何 width 样式属性,并将它们替换为 width:100%。
return match // 替换函数返回修改后的 match 字符串,即替换了 width 属性值后的样式。
newContent = newContent.replace(/<br[^>]/>/gi, '') // 这行代码移除所有 <br> 标签,无论它们是否有属性
newContent = newContent.replace(/<img/gi, '<img style="width:100%;height:auto;display:block;"') // 这行代码为所有 <img> 标签添加了一个内联 style 属性,确保图片的宽度为100%,高度自动,并且作为块级元素显示。
return newContent// 函数返回处理后的HTML内容。

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值