小程序rich-text常见图片问题

rich-text组件为微信小程序富文本解析器,该组件支持富文本解析,但需要对照一套自定义规则的 JOSN 数据格式,API 返回的富文本需要前端做数据转换。

日常开发中该组件的主要用途就是解析html标签,但是在使用中也是有一些问题

这种情况下后端如果不返回富文本,前端去在小程序去处理是比较麻烦的,还得定个规则,前端再写好样式拼接起来。如果后端直接给你返回富文本,用这个去解析可以直接搞定。

Bug & Tip

  1. tip: nodes 不推荐使用 String 类型,性能会有所下降。
  2. tip: rich-text 组件内屏蔽所有节点的事件。
  3. tip: attrs 属性不支持 id ,支持 class
  4. tip: name 属性大小写不敏感。
  5. tip: 如果使用了不受信任的HTML节点,该节点及其所有子节点将会被移除。
  6. tip: img 标签仅支持网络图片。
  7. tip: 如果在自定义组件中使用 rich-text 组件,那么仅自定义组件的 wxss 样式对 rich-text 中的 class 生效。

该组件能解析几乎所有的html标签,其中tableimg标签支持width,问题就出现了,设定了固定的width,除非是百分比,否则还能自适应各个屏幕吗?另外img只支持网络图片,这个大家可以理解,毕竟代码不可能连图片资源一起带过来。

图片不显示

多半这种问题产生的原因就在于你没有使用网络图片,解决方法如下:

服务器后台先对图片地址进行处理,修改为绝对的网络地址

python代码如下

1
2
content = '<p><img class="size-full wp-image-20763 aligncenter" src="/uploads/eb-52019_400-300.jpg" alt="" width="400" /></p><p style="text-align: center;"> EB-5新规出台,投资项目如何选?</strong></span></p>'
content = content.replace('"/uploads/', '"https://www.diandian100.cn/uploads/')

php代码差不多

1
2
$content = '<p><img class="size-full wp-image-20763 aligncenter" src="/uploads/eb-52019_400-300.jpg" alt="" width="400" /></p><p style="text-align: center;"> EB-5新规出台,投资项目如何选?</strong></span></p>'
$content = str_replace('"/uploads/', '"https://www.diandian100.cn/uploads/', $content)

图片宽度超出

考虑到多张图片的话,图片之间会有间隙,不希望有间隙可以加上display:block

处理方法有两种:

  1. 服务器处理

    1
    $content = str_replace("<img ", "<img style='max-width:100%;height:auto;display:block;'", $content);

python

1
content = content.replace("<img ", "<img style='max-width:100%;height:auto;display:block;'");

  1. 小程序处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
     that.setData({
    content: res.data.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
    })

    //或

    that.setData({
    content: res.data.contents.replace('<img ', '<img style="max-width:100%;height:auto;display:block;"')
    })