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

2020-06-29  本文已影响0人  FSYu

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/g, '<img style="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解析富文本(最大的缺点是代码配置多,并且无疑多出了一部分源码资源,作者还不维护了)

上一篇下一篇

猜你喜欢

热点阅读