uni-app小程序图片v-html自适应问题

前端 0 1012
01789034
01789034 LV2 关注 2022年1月24日 16:29 编辑

@TOC

前言

用v-html渲染富文本框,发现小程序图片没有办法自适应
采用css去修改,发现不生效

img{
    width: 750upx!important;
}

解决办法

uni的v-html转换成小程序是rich-text标签,则我们直接使用rich-text来实现富文本的渲染

<rich-text :nodes="details.newsConten | filtersRichText"></rich-text>

我们使用过滤器来把img的标签拿出来,在放css样式

filters: {
    filtersRichText(html) { //控制小程序中图片大小
        let newContent = html.replace(/<img[^>]*>/gi, (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, (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:inline-block;margin:10rpx auto;"');
        return newContent;
    }
},

效果展示

在这里插入图片描述

补充

如果图片想展示自定义样式,那么我们可以不添加style,而改用class,在我们的css中加上class样式也可以

赞(0) 收藏(0)  分享
相关标签:
0个回复
  • 消灭零回复
Vaptcha启动中...