zoukankan      html  css  js  c++  java
  • 微信小程序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
    }
  • 相关阅读:
    Lua基础之Function
    Lua基础之table详解
    Lua基础之语法
    详解C#中的反射(转载)
    Cocos-x 3.2:从C++过渡到Lua(转载)
    cocos2dx-Lua中出现的问题
    (转载)Cocos2dx-OpenGL ES2.0教程:纹理贴图(6)
    (转载)Cocos2dx-OpenGL ES2.0教程:你的第一个立方体(5)
    hdu 2098 分拆素数和(一个偶数拆分成两个不同素数和 拆法数量)
    51Nod
  • 原文地址:https://www.cnblogs.com/lovelh/p/12747497.html
Copyright © 2011-2022 走看看