最近遇到一个问题在小程序中渲染富文本的内容,如果里面有图片和视频,渲染的时候图片大小超屏幕了,而视频完全没有显示!!!
最后通过正则匹配替换后 图片可以了视频还是不行,看了微信小程序api官网才知道不支持视频渲染,那怎么办呢?
最终方法:
formatRichText(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(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replaceAll('style=""', '');
// newContent = newContent.replace(/<br[^>]*\/>/gi, '');
//处理图片
// newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;width:100%;height:auto;vertical-align: middle;"');
//处理媒体
//获取视频的地址
const videoRegex = /<div data-w-e-type="video"[^>]*>[\s\S]*?<\/div>/gi;
const regexSrc = /src="([^"]+)"/
const videoItem = newContent.match(videoRegex);
if (videoItem.length > 0) {
for (let i = 0; i < videoItem.length; i++) {
let src = videoItem[i].match(regexSrc);
this.detailsMedia.push({url: src[1], type: 'video'})
}
}
newContent = newContent.replace(videoRegex, '')
//获取图片地址
const imgRegex = /<img[^>]*\s+src="([^"]+)"[^>]*>/gi
const imgItem = newContent.match(imgRegex);
if (imgItem.length > 0) {
for (let i = 0; i < imgItem.length; i++) {
let src = imgItem[i].match(regexSrc);
this.detailsMedia.push({url: src[1], type: 'image'})
}
}
newContent = newContent.replace(imgRegex, '')
// 获取富文本文本
// 正则表达式 全局匹配 table tr td标签,并给各自标签添加class类名
newContent = newContent.replace(/<table/g, '<table class="table" style="width:100%;"')
newContent = newContent.replace(/<tr/g, '<tr class="tr" style="display: table-row;"')
newContent = newContent.replace(/<td/g, '<td class="td" style="display: table-cell;text-align: left;"')
newContent = newContent.replace(/<ol/g, '<ol class="ol" style="text-align: left;padding-left:20rpx;margin:0;"')
return newContent;
},
通过提取地址,我自己渲染~哈哈哈