小程序 rich-text 富文本的解析显示

wxml

<rich-text nodes="{{text}}"></rich-text>

js

onShow: function() {
  var self = this;
    self.data.text = self.data.text.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"')
    .replace(/em;/g,'rpx;')
    .replace(/<section/g, '<div').replace(/\/section>/g, '/div>');
    
    self.setData({
      text: self.data.text
    })
  }
核心的处理代码
self.data.text.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block"')
或者
self.data.text.replace(/\<img/gi, '<img class="rich-img"');
因发现在后台系统多个图片上传img标签带有一个空style,导致style赋值失败
wxss中:
.rich-img {
  width:100%;
  height:auto;
  display:block;
}

/**
 * 此代码段处理目的为,匹配富文本代码中的 <img> 标签,并将其图片的宽度修改为适应屏幕
 * max-width:100%       --- 图片宽度加以限制,避免超出屏幕
 * height:auto          --- 高度自适应
 * display:block        --- 此代码,可以去掉图片之间的空白间隔,个人觉得好用
 */
一般而言,我们使用的富文本编辑器(比如:UEditor),生成的 `HTML节点及属性` 大多数都可以进行解析
测试中,发现对 `<section>` 标签不支持

所以修改为:
self.data.text = self.data.text.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"')
    .replace(/em;/g,'rpx;')
    .replace(/<section/g, '<div').replace(/\/section>/g, '/div>');

在这之前,我使用的是 wxParse解析富文本(最大的缺点是代码配置多,并且无疑多出了一部分源码资源,作者还不维护了)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容