微信小程序 rich-text 解析富文本以及图片处理

2020-02-20  本文已影响0人  坚果大人的欧尼

最近在写微信小程序的时候,后台返回的是富文本数据,开始想着处理html标签,后来发现可以使用rich-text标签,如下:
.wxml


<view class="hotspot-info-content">

      <rich-text nodes="{{contentInfo}}" class="hotspot-rich-text"></rich-text>

</view>

contentInfo: content.replace('<img ', '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"') 

.js

    wx.request({
        url: '接口地址',
        data: {
          topicId: _id
        },
        header: {
          'content-type': 'application/json'
        },
        method: 'GET',
        responseType: 'text',
        success(res) {
          console.log(res);
          if (res.data.code === 0) {
            //返回的富文本数据
            var content = res.data.data.content;
            that.setData({
            //处理图片自适应问题
           /**
           * 此代码段处理目的为,匹配富文本代码中的 <img> 标签,并将其图片的宽度修改为适应屏幕
           * max-width:100%       --- 图片宽度加以限制,避免超出屏幕
           * height:auto          --- 高度自适应
           * display:block        
          *其他样式可根据自己需要进行添加
           */
              contentInfo: content.replace('<img ', '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"') 
            })
          } else {
            console.log('数据加载失败')
            wx.showToast({
              title: res.data.msg,
              duration: 2000
            })
          }
        },
      })
上一篇 下一篇

猜你喜欢

热点阅读