微信小程序 rich-text 富文本图片自适应

<p :class="item.isMore == true ? 'richText' : 'minH'" v-if="isShow"

v-html="contentConv(item.storyContent)">

</p>

直接在css中加max-width:100%;height:auto; 。没有生效

 方式一:在style中追加 max-width:100%;height:auto; ,此方法优点灵活,对于content中所有图片都起作用

// 文章html正则追加max-width

contentConv(content) {

return content.replace(/<(img).*?(\/>|<\/img>)/g, function(mats) {

if (mats.indexOf('style') < 0) {

return mats.replace(/<\s*img/, '<img style="max-width:100%;height:auto;"');

} else {

return mats.replace(/style=("|')/, 'style=$1max-width:100%;height:auto;')

}

});

},

方式二:此方法会破坏图片设置的样式,再设置style="max-width:100%;height:auto;"

contentConv(content) {

    return content.replace(/<img[^>]*>/gi, function (match, capture) {

      return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:100%;height:auto;"') // 替换style

    });

}

处理前
处理后
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容