<template> <!-- 富文本组件 --> <div class="rich-text" :style="{ 'padding': padding + 'px', 'background': backgroundColor }" > <rich-text :nodes="richText" :space="'nbsp'"></rich-text> </div> </template> <script type="text/ecmascript-6"> /** * 处理富文本里的图片宽度自适应 * 1.去掉img标签里的style、width、height属性 * 2.img标签添加style属性:max-width:100%;height:auto * 3.修改所有style里的width属性为max-width:100% * 4.去掉<br/>标签 * @param html * @returns {void|string|*} */ function 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, ""); let maxWidth = 375; match.replace(/width="(.+?)"/g, function (val, val1) { if (val1 > maxWidth) { match = match .replace(/width="[^"]+"/gi, "") .replace(/width='[^']+'/gi, ""); match = match.replace( /\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"' ); } }); return match; }); newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) { match = match .replace(/ width:[^;]+;/gi, "max-width:100%;") .replace(/ width:[^;]+;/gi, "max-width:100%;"); match = match .replace(/max-width:[^;]+;/gi, "max-width:100%;") .replace(/max-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:block;margin-top:0;margin-bottom:0;"' // ); return newContent; } export default { props: { render: { type: Boolean, default: false, }, datas: { type: Object, default: ()=>{ return {} }, }, }, data() { return {}; }, components: {}, computed: { padding() { return this.datas.componentData.padding; }, backgroundColor() { return this.datas.componentData.backgroundColor; }, richText() { return formatRichText(this.datas.componentData.richText); }, }, created() {}, mounted() {}, methods: {}, }; </script> <style lang="scss" scoped> .rich-text { /deep/ img { max-width: 100% !important; height: auto; } } </style>