“ 在小程序开发中,要显示商品详情,后台给的数据是富文本,图片和文字混杂。
这个时候可以使用微信小程序的rich-text组件,但是这个组件是按照内容的原始html格式进行展示,所以图片宽度过大,就会展示不全。”
比如这样:
解决
wxml文件下
<rich-text nodes="{{content}}" type='text'></rich-text>js文件下
let content = res.content; //重点是这句话 res.content是从后台获取的数据 进行正则匹配的 res.content = content.replace(/\<img/gi, '<img style="width:100%;height:auto" ')这样做是在原来的<img>标签下加了style="width:100%;height:auto",
测试了一下,有一些商品好了。
但是如果原本img中就有style样式, 还是有问题。
所以对正则就行优化:
formatImg:function(html){ var newContent= html.replace(/<img[^>]*>/gi,function(match,capture){ var match = match.replace(/style=\"(.*)\"/gi, ''); return match; }); return newContent; }写了一个方法,把img标签中的style删除
然后再统一加上我们的样式。
newContent.replace(/\<img/gi, '<img style="width:100%;height:auto" ')这样做是因为有的img有style,有的没有。所以如果用replace直接替换,原本没有style的会没有加上我们的style。
完整代码
最后完整的function:
formatImg:function(html){ var newContent= html.replace(/<img[^>]*>/gi,function(match,capture){ var match = match.replace(/style=\"(.*)\"/gi, ''); return match; }); const result = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto" ') return result;}欢迎关注公-众-号:技术笔记与开源分享
感谢