富文本图片宽度自适应样式处理
发布于 1 年前 作者 ryu 4759 次浏览 来自 分享

/**

 * 富文本图片宽度自适应样式处理

 * 1.去掉img标签里的style、width、height属性

 * 2.img标签添加style属性: max-width: 100%;height:auto

 * 3.修改所有style里的width属性为max-width: 100%

 * 4.去掉<br />标签

 * @param {*} html 

 */

function formatRichText(html) {

    //正则匹配img标签,并且含有width,height

    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {

        // 除去data-width 自定义属性

        match = match.replace(/data-width="[^"]+"/gi, '').replace(/data-width='[^']+'/gi, '');


        // style 样式设置及追加

        if (match.indexOf('style'< 0{ //不存在style属性 则设置自适应样式

            match = match.replace(/<\s*img/, '<img style="max-width:100%;height:auto;"')

        } else { // 存在style属性,则追加自适应样式

            match = match.replace(/style=("|')/, 'style=$1max-width:100%;height:auto;')

        }


        // 清除width和height属性

        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');

        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');

        return match;

    });


    // 将所有标签style设置的width替换为max-width:100%

     newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){

         match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');

         return match;

    });


    // 清除<br />换行

    newContent = newContent.replace(/<br[^>]*\/>/gi, '');

    return newContent;

}


回到顶部