zoukankan      html  css  js  c++  java
  • 微信小程序 rich-text 富文本中图片自适应

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

    方法如下:

     1 /**
     2  * 处理富文本里的图片宽度自适应
     3  * 1.去掉img标签里的style、width、height属性
     4  * 2.img标签添加style属性:max-100%;height:auto
     5  * 3.修改所有style里的width属性为max-100%
     6  * 4.去掉<br/>标签
     7  * @param html
     8  * @returns {void|string|*}
     9  */
    10 function formatRichText(html){
    11   let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
    12       match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    13       match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    14       match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    15       return match;
    16   });
    17   newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
    18       match = match.replace(/[^;]+;/gi, 'max-100%;').replace(/[^;]+;/gi, 'max-100%;');
    19       return match;
    20   });
    21   newContent = newContent.replace(/<br[^>]*/>/gi, '');
    22   newContent = newContent.replace(/<img/gi, '<img style="max-100%;height:auto;display:block;margin:10px 0;"');
    23   return newContent;
    24 }
    25 
    26 
    27 // 模块出口
    28 module.exports = {
    29   formatRichText,
    30 };

    转载于:https://www.cnblogs.com/lovelh/p/12747497.html

  • 相关阅读:
    Java基础-String、StringBuffer、StringBuilder的区别
    Java基础-String类能被继承吗,为什么
    Java基础-Java中的基本数据类型是什么,各自占用多少字节
    JAVA关键字
    Java 栈(stack)与堆(heap) 详解
    Hibernate--hibernate.hbm.xml详解
    Hhibernate--映射继承关系
    C--c语言模拟java的linkedList
    C--调试基本命令
    C--指针
  • 原文地址:https://www.cnblogs.com/Jessie-candy/p/13217666.html
Copyright © 2011-2022 走看看