在写小程序项目的过程中,发现有时候后端返回来的富文本里边嵌套着图片,但是图片的大小很大,溢出了屏幕,所以我们得把图片调整成合适大小
//html
<template>
<view>
<rich-text :nodes="text"></rich-text>
<rich-text :nodes="text"></rich-text>
</view>
</template>
//data的数据,模拟接口返回来的数据(摘自某个接口)
data() {
return {
text:"<p><img src=\"http://kuajing.shs.broing.cn/uploads/20230221/f5be91bd0313e35b8f612907814ca349.jpg\" width=\"591\" height=\"538\" alt=\"\" style=\"width: 591px; height: 538px;\"/></p>"
};
},
//方法
format(html) {
var GRT = [
// img 样式
['img', "max-width:100%;height:auto;"],
];
for (let i = 0; i < GRT.length; i++) {
html = html.replace(new RegExp('<' + GRT[i][0] + '>|<' + GRT[i][0] + ' (.*?)>', 'gi'), function(word) {
// 分析 dom 上是否带有 style=""
if (word.indexOf('style=') != -1) {
var regIn = new RegExp('<' + GRT[i][0] + '(.*?)style="(.*?)"(.*?)(/?)>', 'gi');
return word.replace(regIn, '<' + GRT[i][0] + '$1style="$2 ' + GRT[i][1] + '"$3$4>');
} else {
var regIn = new RegExp('<' + GRT[i][0] + '(.*?)(/?)>', 'gi');
return word.replace(regIn, '<' + GRT[i][0] + '$1 style="' + GRT[i][1] + '$2">');
}
});
}
return html;
}
最后效果如下:
![]() |
![]() |
富文本中文字超出显示不全解决方式
可以给rich-text添加该类名
.rich-txt{
word-break: break-all; //允许在单词内换行
white-space: pre-line; //合并空白符序列,保留换行符
}