微信小程序富文本图片、换行问题

在微信小程序开发中,使用 rich-text 富文本标签经常碰到图片超出屏幕宽度,空白换行不起作用的问题,解决思路是使佣正则匹配对应的标签,增加默认的样式,代码如下

/**
 * 追加节点行内样式
 * @param {String} html 富文本字符串
 * @param {String} nodeName 匹配节点的名称
 * @param {String} style 追加的行内样式
 * @returns {String}
 */
const appendNodeLineStyle = (html, nodeName, style) => {
  const reg = new RegExp(`<${nodeName}.*?>`, 'ig')
  return html.replace(reg, match => {
    // 检测是否有 `style` 属性
    if (match.indexOf('style=') !== -1) {
      // 在原有的 `style` 属性后面加上新的行内样式
      return match.replace(/style="(.*?)"/, `style="${style}$1"`);
    } else {
      // 否则直接添加 `style` 属性和行内样式属性
      return match.replace(/<img/, `<img style="${style}"`);
    }
  })
}

/**
 * 格式化富文本内容
 * @param {string } html
 * @returns {string}
 */
const formatRichText = (html) => {
  if (typeof html !== 'string') {
    html = ''
  }
  // 解决图片宽度不能自适应的问题
  html = appendNodeLineStyle(html, 'img', 'max-width:100%;height:auto;')
  // 解决 `p` 标签在后台有默认的上下外边距,到小程序里没有上下外边距的问题
  html = appendNodeLineStyle(html, 'p', 'margin-block-start:1em;margin-block-end:1em;')
  // 解决微信小程序会忽略空白换行的问题
  html = html.replace(/&nbsp;/g, '\u00A0')

  return html
}

接着调用上面的方法,即可处理好替换后的 html 字符串,示例如下:

// 例如 `data` 是后端返回的接口数据
const data = {
  id: 1,
  // 富文本字符串
  rich: ''
}

this.setData({
  detail: {
    ...data,
    rich: formatRichText(data.rich)
  }
})
<rich-text nodes="{{detail.rich}}"></rich-text>

以上代码也只是处理一些简单的富文本问题,想要让富文本有更多功能,如:点击图片可以预览、图片懒加载等,需要使用一些第三方插件,推荐一个好用富文本插件

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值