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

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

<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

    })

}

res.data.goodsDetail.detail = res.data.goodsDetail.detail.replace(/<p([\s\w"=\/\.:]+)((?:(style="[^"]+")))/ig, '<p')

.replace(/<p>/ig, '<p style="font-size: 15pxline-height: 25px">')

.replace(/<img([\s\w"-=\/\.:]+)((?:(height="[^"]+")))/ig, '<img$1')

.replace(/<img([\s\w"-=\/\.:]+)((?:(width="[^"]+")))/ig, '<img$1')

.replace(/<img([\s\w"-=\/\.:]+)((?:(style="[^"]+")))/ig, '<img$1')

.replace(/<img([\s\w"-=\/\.:]+)((?:(alt="[^"]+")))/ig, '<img$1')

.replace(/<img([\s\w"-=\/\.:]+)/ig, '<img style="width: 100%" $1')


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/12203522.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-21
下一篇2023-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存