小程序富文本图片大小问题
文章目录
- 概要
- uniapp小程序情况
- 解决方法及完整示例
概要
在小程序使用富文本或者在nuiapp(小程序的)使用富文本都会转为
<rich-text nodes="<p class="p class">内容</p>”></rich-text>
如果是这种情况的话在css里面就使用不了穿透样式了
/deep/{}
uniapp小程序情况
pc:小程序里面的v-html里面什么东西东不能有,包括注释,否则会报错
<view class="dowm">
<view class="" v-html="ggDetailForm.msgContent">
</view>
</view>
用uniapp写小程序在里面会自动转为
<rich-text nodes="<p class="p class">内容</p>”></rich-text>
解决方法及完整示例
使用正则来修改富文本图片样式
function formatRichText(html){
console.log(html);
let newContent= html.replace(/<img[^>]*>/gi,function(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,function(match,capture){
match = match
.replace(/<p>/gi, '<p class="p_class">')
.replace(/width:[^;]+;/gi, 'max-width:100%;')
.replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, "");
newContent = newContent.replace(/<a>/gi, '<a class="p_class "');
newContent = newContent.replace(/<li>/gi, '<li class="p_class "');
newContent = newContent.replace(/\<p/gi, '<p class="p_class "');
newContent = newContent.replace(/\<span/gi, '<span class="p_class "');
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
return newContent;
}
export default {
data() {
return {
formatRichText:formatRichText,
}
},
methods: {
ggDetail(id) {
let obj = {
id: id,
}
let that = this
uni.$u.http
.get('接口', {
params: obj,
})
.then(res => {
if (res.success) {
that.ggDetailForm = res.result
if(that.ggDetailForm.content){
that.ggDetailForm.content = that.formatRichText(that.ggDetailForm.content)
}
}
})
},
},
}