原生微信小程序解析富文本编辑器(TinyMCE)html代码

普歌-码上鸿鹄:小程序解析HTML代码

前言:在一些资讯性的文章需要简单排版时,会用到富文本编辑器,但是富文本编辑器生成的是一些html代码,在小程序中无法使用,下面看看两种解决方法。

一、用微信文档提供的rich-text

<!-->content是API获取的html代码</-->
<rich-text nodes="{{content}}"></rich-text>

*注意:用rich-text不会达到直接想要的结果,比如图片大小最大宽度不是100%,需要自己用js控制

  • 3.下面是处理html样式自适应的代码
/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性:max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉
标签
 */
function formatRichText(html){
    let newContent= html.replace(/]*>/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, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
    });
    newContent = newContent.replace(/]*\/>/gi, '');
    newContent = newContent.replace(/\, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
    return newContent;
  }
  • 解决完这个,不知道还会有没有其他不可预知的问题,我开发时用的是下一种方法

二、用插件WxParse解析html

  1. 这是GitHub上大神封装的插件,我开发时用的是这个方法,但是作者不维护了,大家选择性用
  2. 先放上下载地址WxParse,或者可以GitHub上直接搜索WxParse,第一个就是
  3. 使用步骤
  • 先下载压缩包
    github下载
  • 然后将文件夹中的wxParse解压到需要的项目中
    拷贝
  • 在项目里引用,分别在js, wxml,wxss引用
    JS:
    js描述
var WxParse = require('../../utils/wxParse/wxParse.js')
...
...
//方法中使用
    getdetaul: function (id) {
           let that = this;
       getDescApi.getdesc(id).then((res) => {
             console.log(res.data);
             that.setData({
               model: res.data,
             });
             WxParse.wxParse("contents", "html", res.data.content, that, 0);
           });
         },

WXML:

<import src="../../utils/wxParse/wxParse.wxml"/>
  <view>
        <template is="wxParse" data="{{wxParseData:contents.nodes}}"/>
  </view>

WXSS:

/* wxss样式引入*/  
@import "../../utils/wxParse/wxParse.wxss";

以上就是小程序解决解析html代码的方法

更多推荐:wantLG的《普歌-码上鸿鹄团队:微信小程序使用阿里巴巴iconfont矢量多色图标


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wantLG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值