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

  • 相关阅读:
    Springboot学习:核心配置文件
    Springboot学习:底层依赖与自动配置的原理
    Springboot学习:介绍与HelloWorld
    js根据时间戳倒计时
    windows phone 豆瓣api的封装
    Android开发初始
    PHP(一)
    程序员修炼之道(一)
    WebClient和HttpReuqest两种网络请求的方式
    黑客与画家(二)
  • 原文地址:https://www.cnblogs.com/Jessie-candy/p/13217666.html
Copyright © 2011-2022 走看看