【uni-app】rich-text的使用

rich-text的使用

rict-text可以支持部分HTML节点及属性
rict-text的属性如下:
在这里插入图片描述
nodes 值为 HTML String 时,在组件内部将自动解析为节点列表,推荐直接使用 Array 类型避免内部转换导致的性能下降。App-nvue 和支付宝小程序不支持 HTML String 方式,仅支持直接使用节点列表即 Array 类型,如要使用 HTML String,则需自己将 HTML String 转化为 nodes 数组,可使用 html-parser (opens new window)转换。

例如:

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


htmlSnip: [{
        name: 'div',
        attrs: {
            class: 'div-class',
            style: 'line-height: 60px; color: red; text-align:center;'
        },
        children: [{
            type: 'text',
            text: 'Hello&nbsp;uni-app!'
        }]
    }],

有时候展现的图片也是没有样式的,导致图片会按照原始大小显示,超出界面框架。我们需要用正则将内容转义一下:
新建一个js文件 replaceImg.js:

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性:max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html){
  let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
      match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
      return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
  return newContent;
}

// module.exports = {
//   formatRichText
// }

module.exports = {
  formatRichText: formatRichText
}

在对应的界面调用:

var replace_img = require("../../../utils/replaceImg.js");

//request
let data_article = res.data.data[0];//这里是请求到的 html 内容
var newsArticle = replace_img.formatRichText(data_article.content);
that.setData({
  art_content:newsArticle
});
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值