• 微信小程序rich-text富文本中有图片时需要自适应


    如果文本中的图片只有<img src="">那么可以直接替换,但是如果有其他的样式比如width,height,style时就需要先去掉其,再替换

    方法如下:

    /**
     * 处理富文本里的图片宽度自适应
     * 1.去掉img标签里的style、width、height属性
     * 2.img标签添加style属性:max-100%;height:auto
     * 3.修改所有style里的width属性为max-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, '');
          return match;
      });
      newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
          match = match.replace(/[^;]+;/gi, '100%;').replace(/[^;]+;/gi, '100%;');
          return match;
      });
      newContent = newContent.replace(/<br[^>]*/>/gi, '');
      newContent = newContent.replace(/<img/gi, '<img style="100%;height:auto;display:block;margin:10px 0;"');
      return newContent;
    }

    // module.exports = {
    //   formatRichText
    // }

    module.exports = {
      formatRichText: formatRichText
    }
  • 相关阅读:
    Beta冲刺(5/7)——2019.5.26
    Beta冲刺(4/7)——2019.5.25
    Beta冲刺(3/7)——2019.5.24
    Echo团队Beta冲刺随笔集合
    Echo团队Alpha冲刺随笔集合
    用户体验报告(Echo)
    Echo团队 对 待就业六人组 和 SkyReach 的Beta产品测试报告
    Beta冲刺第七天
    Beta冲刺第六天
    Beta冲刺第五天
  • 原文地址:https://www.cnblogs.com/lovelh/p/12747497.html
Copyright © 2020-2023  润新知