@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样式也可以