uniapp开发微信小程序遇到富文本内容大小变形问题v-html
<view class="description">
<view>论坛介绍</view>
<view class="html-content" v-html="forumDetailData.forumDescriptionCn"></view>
</view>
this.forumDetailData.forumDescriptionCn = this.forumDetailData.forumDescriptionCn
// 1. px 转 rem
.replace(/(\d+)px/g, (match, p1) => {
return (p1 * 0.04) + 'rem';
})
// 2. 给 id="companyBox" 添加 margin 样式
.replace(/<(\w+)([^>]*?)id=["']companyBox["']([^>]*?)>/gi, (match, tag, beforeId,
afterId) => {
let fullAttr = beforeId + afterId;
if (/style\s*=\s*["'].*?["']/.test(fullAttr)) {
return match.replace(/style=["'](.*?)["']/i, (styleMatch,
styleContent) => {
return `style="${styleContent} margin: 1rem 0;"`;
});
} else {
return `<${tag}${beforeId}id="companyBox"${afterId} style="margin: 1rem 0;">`;
}
})
// 3. 背景图处理,追加 background-size: 80%
.replace(/style=["'](.*?)["']/gi, (match, styleContent) => {
if (/background(-image)?:\s*url\(['"]?.*?['"]?\)/.test(styleContent)) {
if (/background-size\s*:/.test(styleContent)) {
return match; // 已有 background-size
} else {
return `style="${styleContent} background-size: 80%;"`;
}
}
return match;
})
// 4. 给 <img> 添加样式,防止样式失效
.replace(/<img /g,
'<img style="max-width:100%;height:auto;display:block;margin-bottom:10rpx;" ');