<rich-text :nodes="repairRichText('<b>您的富文本内容</b>')" />
            /**
            * 修复富文本图片宽度
            * @description 解决图片宽高超出显示不全问题(让其自适应)
            * @param {String} html - 富文本
            * @return String
            */
            repairRichText(html) {
                // 去掉<img>中style /width / height属性
                let newContent = html.replace(/<img[^>]*>/gi, (match) => {
                    match = match.replace(/style="[^"]+"/gi,                        '').replace(/style='[^']+'/gi, '')
                    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
                    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
                    match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '') // 去除 style=""这样的属性
                    return match
                })
                // 修改所有style里的width属性为max-width:100%
                newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
                    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;')
                    return match
                })

                // 去掉所有<br/>标签
                newContent = newContent.replace(/<br[^>]*\/>/gi, '')
                // img标签添加style属性:max-width:100%;height:auto
                newContent = newContent.replace(/\<img/gi,
                    '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
                )
                return newContent;
            },

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐