欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

小程序的四次元口袋:editor富文本编辑器的使用、渲染,以及rich-text进行解析

程序员文章站 2024-01-03 21:51:34
...

editor富文本

1、介绍

富文本编辑器,可以对图片、文字进行编辑。极大地丰富了我们文章的结构样式,之前小程序还没有自己开发富文本插件,而在2019年微信小程序正式发布了富文本api。

支持的类型 编辑器导出内容支持带标签的 html和纯文本的 text,编辑器内部采用 delta 格式进行存储。
setContents 通过setContents接口设置内容时,解析插入的 html 可能会由于一些非法标签导致解析错误,建议开发者在小程序内使用时通过 delta 进行插入。
EditorContext 实例 EditorContext 实例,可通过 wx.createSelectorQuery 获取。

EditorContext 通过 id 跟一个 editor 组件绑定,操作对应的 editor 组件。

这是微信小程序开发的官方文档:https://developers.weixin.qq.com/miniprogram/dev/component/editor.html

属性 类型 默认值 必填 说明 最低版本
read-only boolean false 设置编辑器为只读 2.7.0
placeholder string   提示信息 2.7.0
show-img-size boolean false 点击图片时显示图片大小控件 2.7.0
show-img-toolbar boolean false 点击图片时显示工具栏控件 2.7.0
show-img-resize boolean false 点击图片时显示修改尺寸控件 2.7.0
bindready eventhandle   编辑器初始化完成时触发 2.7.0
bindfocus eventhandle   编辑器聚焦时触发,event.detail = {html, text, delta} 2.7.0
bindblur eventhandle   编辑器失去焦点时触发,detail = {html, text, delta} 2.7.0
bindinput eventhandle   编辑器内容改变时触发,detail = {html, text, delta} 2.7.0
bindstatuschange eventhandle   通过 Context 方法改变编辑器内样式时触发,返回选区已设置的样式 2.7.0

支持的标签有:

类型 节点
行内元素 <span> <strong> <b> <ins> <em> <i> <u> <a> <del> <s> <sub> <sup> <img>
块级元素 <p> <h1> <h2> <h3> <h4> <h5> <h6> <hr> <ol> <ul> <li>

支持的内联样式:

类型 样式
块级样式 text-align direction margin margin-top margin-left margin-right margin-bottom
padding padding-top padding-left padding-right padding-bottom line-height text-indent
行内样式 font font-size font-style font-variant font-weight font-family
letter-spacing text-decoration color background-color

 

2、使用

注意:当前富文本编辑器的图片格式只支持网络图片,不支持本地图片注意这点。

(1)首先我们需要下载富文本编辑器的样式文件,所有的都得自己自行下载。

 我们将文件进行解压后放在小程序项目文件中,以备使用:

小程序的四次元口袋:editor富文本编辑器的使用、渲染,以及rich-text进行解析

 在这里,我也贴出我的iconfont文件。

@font-face {font-family: "iconfont";
  src: url('//at.alicdn.com/t/font_945958_zfsfjju1dim.eot?t=1547618146468'); /* IE9 */
  src: url('//at.alicdn.com/t/font_945958_zfsfjju1dim.eot?t=1547618146468#iefix') format('embedded-opentype'), /* IE6-IE8 */
  url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAABdkAAsAAAAALvAAABcWAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCKSgrBdLN+ATYCJAOBZAt0AAQgBYRtB4YRG7smRSQnqz4jqjWV7P9bAidjcG3cMssRirV6WRdYIhSPI7KwpqTEWqtc6K4YeK6yr9OvxbcdprxM/yib6gio0BZ+n7Rt/V9XwX9lINMYSgkPeG++5I+ba4GUClKqlqSIS6hYyq38QNv8d5x65OEhRh+sdQE7jL5NnPgnihL75TgDFuUqOW2WuvRY8VkVv8LJj8Zl6Y80f+Xx8HZ7/9/tWGoR13aUWBZEaSABZpQkkIVz9psLXwo4ADJiSk74UeimQCl/LdkLu3A5Lb9fLdiAfKs0jVd6s5bW0vrllU9aXUOpAIbgIBQAP4AF4GQAwNjv66z+twPSe3YyEXkJoUQ7zmyGcJHc2NVJ3y0N0HJgEQJLfBSQrqKmOVa8TZaSWNiEpAWmBqH+vylGDwgxZs4BANAGCCDwC//E1Xjv8RV9Igu2Cl/+HldFYWn3eMChdGNoISXOzb/OdLV8cYCdC0/AGw1beE226f8vwwcrF1k++JYDtkM61rHsAPEEG2Or7ysYCtZdilMAh63AY6e+jmP3qVBzmePWPyDU3kl9GHOfD1sDjzw0JUUixbX+Wp8hgFtelxinUgsImeg1AURf5lWDUKiZim3BSbAlb2vGLpQztwwCn/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yIqpO21fY8mOQgksPikzxgiec4uzy7O9e+QMZjIEVfmSqTIiuCr7K2VBZ3zWR18iUrOLHX10/l5sfkOZ8pXe20XAQICaZnc1p2ZKB4rzizakb/+PWQkDgiKLR5m/gwFEd185tKZCw3pHWOtLVbFGq0YV4TwQsbWD7xK5i3hyDk1XqaWd1ZCijhjUxi1J+dkT4UuOyteqeYlY/RtlRZeJUUJRIsRK078bw6UPwv+xKSUSkhYRFRMXEJSSlpGVk5eQVFJWUVVTV1DU0tbR1dP38DQyNjE1MzcwtLKuqMVtT9KrP0JsUaWhk/CabMH/1WRdjgofKhATi2CxnB6Kc7qZla3Xb1rvDmEkOpGHXBFuD7SINgxnJYb5Z0PvcQI6jT0SOp4dn91nRNwSUta6ARsfSrT/P5vrM0kdBlqntqCG1lks6Vi93QlOr5u97aonh1FOcnBq8QdR4wqExkrzaW5f7AmNj1NAZWQ59MgTpjaSWhFdE8Bzh0XaWepES2wsqlbKXHE5wTUKpANbiJqQ1/wLpp3lYWQnFrDTohLqtfi9jptUg3kCLtlZoZno1PtjMaWeGvjTgYTSTOQE0StHQlpoAqaOVCfpXzbpCRQaWD7KwT3FdwTiSlf2LcJ8qJC/TVUrrYJNqlXbggl6/ttgSM2d8kX1mqbHHAnBUpPOkmB6pCGS0w1xScmAefUjxbZ1IAvot2ro1f15aBkAFI/1KCIzd4e') format('woff2'),
  url('//at.alicdn.com/t/font_945958_zfsfjju1dim.woff?t=1547618146468') format('woff'),
  url('//at.alicdn.com/t/font_945958_zfsfjju1dim.ttf?t=1547618146468') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
  url('//at.alicdn.com/t/font_945958_zfsfjju1dim.svg?t=1547618146468#iconfont') format('svg'); /* iOS 4.1- */
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-redo:before {
  content: "\e627";
}

.icon-undo:before {
  content: "\e633";
}

.icon-indent:before {
  content: "\eb28";
}

.icon-outdent:before {
  content: "\e6e8";
}

.icon-fontsize:before {
  content: "\e6fd";
}

.icon-format-header-1:before {
  content: "\e860";
}

.icon-format-header-4:before {
  content: "\e863";
}

.icon-format-header-5:before {
  content: "\e864";
}

.icon-format-header-6:before {
  content: "\e865";
}

.icon-clearup:before {
  content: "\e64d";
}

.icon-preview:before {
  content: "\e631";
}

.icon-date:before {
  content: "\e63e";
}

.icon-fontbgcolor:before {
  content: "\e678";
}

.icon-clearedformat:before {
  content: "\e67e";
}

.icon-font:before {
  content: "\e684";
}

.icon-723bianjiqi_duanhouju:before {
  content: "\e65f";
}

.icon-722bianjiqi_duanqianju:before {
  content: "\e660";
}

.icon-text_color:before {
  content: "\e72c";
}

.icon-format-header-2:before {
  content: "\e75c";
}

.icon-format-header-3:before {
  content: "\e75d";
}

.icon--checklist:before {
  content: "\e664";
}

.icon-baocun:before {
  content: "\ec09";
}

.icon-line-height:before {
  content: "\e7f8";
}

.icon-quanping:before {
  content: "\ec13";
}

.icon-direction-rtl:before {
  content: "\e66e";
}

.icon-direction-ltr:before {
  content: "\e66d";
}

.icon-selectall:before {
  content: "\e62b";
}

.icon-fuzhi:before {
  content: "\ec7a";
}

.icon-shanchu:before {
  content: "\ec7b";
}

.icon-bianjisekuai:before {
  content: "\ec7c";
}

.icon-fengexian:before {
  content: "\ec7f";
}

.icon-dianzan:before {
  content: "\ec80";
}

.icon-charulianjie:before {
  content: "\ec81";
}

.icon-charutupian:before {
  content: "\ec82";
}

.icon-wuxupailie:before {
  content: "\ec83";
}

.icon-juzhongduiqi:before {
  content: "\ec84";
}

.icon-yinyong:before {
  content: "\ec85";
}

.icon-youxupailie:before {
  content: "\ec86";
}

.icon-youduiqi:before {
  content: "\ec87";
}

.icon-zitidaima:before {
  content: "\ec88";
}

.icon-xiaolian:before {
  content: "\ec89";
}

.icon-zitijiacu:before {
  content: "\ec8a";
}

.icon-zitishanchuxian:before {
  content: "\ec8b";
}

.icon-zitishangbiao:before {
  content: "\ec8c";
}

.icon-zitibiaoti:before {
  content: "\ec8d";
}

.icon-zitixiahuaxian:before {
  content: "\ec8e";
}

.icon-zitixieti:before {
  content: "\ec8f";
}

.icon-zitiyanse:before {
  content: "\ec90";
}

.icon-zuoduiqi:before {
  content: "\ec91";
}

.icon-zitiyulan:before {
  content: "\ec92";
}

.icon-zitixiabiao:before {
  content: "\ec93";
}

.icon-zuoyouduiqi:before {
  content: "\ec94";
}

.icon-duigoux:before {
  content: "\ec9e";
}

.icon-guanbi:before {
  content: "\eca0";
}

.icon-shengyin_shiti:before {
  content: "\eca5";
}

.icon-Character-Spacing:before {
  content: "\e964";
}

(2) 进行样式布局

test.wxml

<!-- pages/share-items/addJingyan.wxml -->
<view class="page eidt-detail-images-container">
    <view>
        <view class='wrapper'>
            <view class='toolbar' bindtap="format">
                <i class="iconfont icon-zitijiacu {{formats.bold ? 'ql-active' : ''}}" data-name="bold"></i>
                <i class="iconfont icon-zitixieti {{formats.italic ? 'ql-active' : ''}}" data-name="italic"></i>
                <i class="iconfont icon-zitixiahuaxian {{formats.underline ? 'ql-active' : ''}}" data-name="underline"></i>
                <i class="iconfont icon-zitishanchuxian {{formats.strike ? 'ql-active' : ''}}" data-name="strike"></i>
                <i class="iconfont icon-zuoduiqi {{formats.align === 'left' ? 'ql-active' : ''}}" data-name="align" data-value="left"></i>
                <i class="iconfont icon-juzhongduiqi {{formats.align === 'center' ? 'ql-active' : ''}}" data-name="align" data-value="center"></i>
                <i class="iconfont icon-youduiqi {{formats.align === 'right' ? 'ql-active' : ''}}" data-name="align" data-value="right"></i>
                <i class="iconfont icon-zuoyouduiqi {{formats.align === 'justify' ? 'ql-active' : ''}}" data-name="align" data-value="justify"></i>
                <i class="iconfont icon-line-height {{formats.lineHeight ? 'ql-active' : ''}}" data-name="lineHeight" data-value="2"></i>
                <i class="iconfont icon-Character-Spacing {{formats.letterSpacing ? 'ql-active' : ''}}" data-name="letterSpacing" data-value="2em"></i>
                <i class="iconfont icon-722bianjiqi_duanqianju {{formats.marginTop ? 'ql-active' : ''}}" data-name="marginTop" data-value="20px"></i>
                <i class="iconfont icon-723bianjiqi_duanhouju {{formats.micon-previewarginBottom ? 'ql-active' : ''}}" data-name="marginBottom" data-value="20px"></i>
                <i class="iconfont icon-clearedformat" bindtap="removeFormat"></i>
                <i class="iconfont icon-font {{formats.fontFamily ? 'ql-active' : ''}}" data-name="fontFamily" data-value="Pacifico"></i>
                <i class="iconfont icon-fontsize {{formats.fontSize === '24px' ? 'ql-active' : ''}}" data-name="fontSize" data-value="24px"></i>
                <i class="iconfont icon-text_color {{formats.color === '#0000ff' ? 'ql-active' : ''}}" data-name="color" data-value="#0000ff"></i>
                <i class="iconfont icon-fontbgcolor {{formats.backgroundColor === '#00ff00' ? 'ql-active' : ''}}" data-name="backgroundColor" data-value="#00ff00"></i>
                <i class="iconfont icon-date" bindtap="insertDate"></i>
                <i class="iconfont icon--checklist" data-name="list" data-value="check"></i>
                <i class="iconfont icon-youxupailie {{formats.list === 'ordered' ? 'ql-active' : ''}}" data-name="list" data-value="ordered"></i>
                <i class="iconfont icon-wuxupailie {{formats.list === 'bullet' ? 'ql-active' : ''}}" data-name="list" data-value="bullet"></i>
                <i class="iconfont icon-undo" bindtap="undo"></i>
                <i class="iconfont icon-redo" bindtap="redo"></i>
                <i class="iconfont icon-outdent" data-name="indent" data-value="-1"></i>
                <i class="iconfont icon-indent" data-name="indent" data-value="+1"></i>
                <i class="iconfont icon-fengexian" bindtap="insertDivider"></i>
                <i class="iconfont icon-charutupian" bindtap="insertImage"></i>
                <i class="iconfont icon-format-header-1 {{formats.header === 1 ? 'ql-active' : ''}}" data-name="header" data-value="{{1}}"></i>
                <i class="iconfont icon-format-header-2 {{formats.header === 2 ? 'ql-active' : ''}}" data-name="header" data-value="{{2}}"></i>
                <i class="iconfont icon-format-header-3 {{formats.header === 3 ? 'ql-active' : ''}}" data-name="header" data-value="{{3}}"></i>
                <i class="iconfont icon-format-header-4 {{formats.header === 4 ? 'ql-active' : ''}}" data-name="header" data-value="{{4}}"></i>
                <i class="iconfont icon-zitixiabiao {{formats.script === 'sub' ? 'ql-active' : ''}}" data-name="script" data-value="sub"></i>
                <i class="iconfont icon-zitishangbiao {{formats.script === 'super' ? 'ql-active' : ''}}" data-name="script" data-value="super"></i>
                <i class="iconfont icon-quanping"></i>
                <i class="iconfont icon-shanchu" bindtap="clear"></i>
                <i class="iconfont icon-direction-rtl {{formats.direction === 'rtl' ? 'ql-active' : ''}}" data-name="direction" data-value="rtl"></i>
            </view>
            <editor id="editor" class="ql-container" placeholder="{{placeholder}}" showImgSize showImgToolbar showImgResize bindstatuschange="onStatusChange" read-only="{{readOnly}}" bindready="onEditorReady"></editor>
        </view>
    </view>
    <view class="ajc" style="margin:10px;">
        <button type="primary" bindtap="toDeatil">查看生成页面</button>
    </view>
</view>

test.wxss

/* pages/share-items/editJingyan.wxss *//* pages/share-items/addJingyan.wxss *//* pages/share-items/addBlogItem.wxss */
/* 引入editor富文本编辑器样式 */
@import "../../editor/iconfont.wxss";



.eidt-detail-images-container .btn-container {
    margin-top: 20rpx;
}

.eidt-detail-images-container .btn-container .btn-view {
    padding: 0rpx 32rpx 32rpx 32rpx;
}

.eidt-detail-images-container .btn-container .btn-view button {
    border-radius: 0rpx;
}

.wrapper {
    padding: 5px;
    
}

.iconfont {
    display: inline-block;
    padding: 8px 8px;
    width: 24px;
    height: 24px;
    cursor: pointer;
    font-size: 20px;
}

.toolbar {
    box-sizing: border-box;
    border: 2rpx solid red;

    font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
}

.ql-container {
    box-sizing: border-box;
    padding: 12px 15px;
    width: 100%;
    min-height: 50vh;
    height: 100%;
    background: #fff;
    margin-top: 20px;
    font-size: 16px;
    line-height: 1.5;
    border: 1px solid #eee;
}

.ql-active {
    color: #06c;
}

.title{
  font-weight: bold;
  font-size: 20px;
  margin: 10rpx;
}

test.js

// 查看事件文档https://developers.weixin.qq.com/miniprogram/dev/api/media/editor/EditorContext.html
const app = getApp();
Page({
  data: {
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '介绍一下你的详情吧,支持文字和图片...',
    _focus: false,
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad() {

  },
  // 编辑器初始化完成时触发
  onEditorReady() {
    const that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
    }).exec();
  },
  undo() {
    this.editorCtx.undo();
  },
  redo() {
    this.editorCtx.redo();
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset;
    if (!name) return;
    // console.log('format', name, value)
    this.editorCtx.format(name, value);
  },
  // 通过 Context 方法改变编辑器内样式时触发,返回选区已设置的样式
  onStatusChange(e) {
    const formats = e.detail;
    this.setData({
      formats
    });
  },
  // 插入分割线
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    });
  },
  // 清除
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    });
  },
  // 移除样式
  removeFormat() {
    this.editorCtx.removeFormat();
  },
  // 插入当前日期
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    });
  },
  // 插入图片
  insertImage() {
    wx.chooseImage({
      count: 1,
      success: () => {
        this.editorCtx.insertImage({
          src: 'https://profile.csdnimg.cn/7/2/3/2_qq_36789311',
          width: '100%',
          data: {
            id: 'abcd',
            role: 'god'
          },
          success: () => {
            console.log('insert image success')
          }
        })
      }
    });
  },
  //选择图片
  chooseImage(e) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths);
        this.data.images = images.length <= 3 ? images : images.slice(0, 3);
      }
    })
  },
  //查看详细页面
  toDeatil() {
    this.editorCtx.getContents({
      success: (res) => {
        console.log(res.html)
        app.globalData.html = res.html
        wx.navigateTo({
          url: '/pages/detail/detail'
        })

      },
      fail: (res) => {
        console.log("fail:", res);
      }
    });
  },

  // 当是博客本人点击编辑时,进行事件触发
  onEdit(){
    
  }
})

演示结果如下

小程序的四次元口袋:editor富文本编辑器的使用、渲染,以及rich-text进行解析

 

3、富文本解析

 为了方便演示,我们另外添加一组page文件,通过富文本进行解析显示。

show.wxml

<!-- pages/details/details.wxml -->
<rich-text nodes="{{html}}"></rich-text>
<view class="ajc">
    <button type="primary" bindtap="back">返回</button>
</view>

show.wxss

/* pages/detail/detail.wxss */
page{
    box-sizing: border-box;
    padding: 12px 15px;
    width: 100%;
    min-height: 50vh;
    height: 100%;
    background: #fff;
    margin-top: 20px;
    font-size: 16px;
    line-height: 1.5;
}

show.js

// pages/details/details.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      html: app.globalData.html
    })
  },
  // 返回0
  back() {
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

最后显示如下:

 

小程序的四次元口袋:editor富文本编辑器的使用、渲染,以及rich-text进行解析

4、给富文本预先设置内容

很简单,只需对之前的test.js文件重新修改下即可。

// 查看事件文档https://developers.weixin.qq.com/miniprogram/dev/api/media/editor/EditorContext.html
const app = getApp();
Page({
  data: {
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '介绍一下你的详情吧,支持文字和图片...',
    _focus: false,
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad() {

  },
  // 编辑器初始化完成时触发
  onEditorReady() {
    // const that = this;
    // wx.createSelectorQuery().select('#editor').context(function (res) {
    //   that.editorCtx = res.context;
    // }).exec();
    this.editContent()
  },
  undo() {
    this.editorCtx.undo();
  },
  redo() {
    this.editorCtx.redo();
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset;
    if (!name) return;
    // console.log('format', name, value)
    this.editorCtx.format(name, value);
  },
  // 通过 Context 方法改变编辑器内样式时触发,返回选区已设置的样式
  onStatusChange(e) {
    const formats = e.detail;
    this.setData({
      formats
    });
  },
  // 插入分割线
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    });
  },
  // 清除
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    });
  },
  // 移除样式
  removeFormat() {
    this.editorCtx.removeFormat();
  },
  // 插入当前日期
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    });
  },
  // 插入图片
  insertImage() {
    wx.chooseImage({
      count: 1,
      success: () => {
        this.editorCtx.insertImage({
          src: 'https://profile.csdnimg.cn/7/2/3/2_qq_36789311',
          width: '100%',
          data: {
            id: 'abcd',
            role: 'god'
          },
          success: () => {
            console.log('insert image success')
          }
        })
      }
    });
  },
  //选择图片
  chooseImage(e) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths);
        this.data.images = images.length <= 3 ? images : images.slice(0, 3);
      }
    })
  },
  //查看详细页面
  toDeatil() {
    this.editorCtx.getContents({
      success: (res) => {
        console.log(res.html)
        app.globalData.html = res.html
        wx.navigateTo({
          url: '/pages/detail/detail'
        })

      },
      fail: (res) => {
        console.log("fail:", res);
      }
    });
  },
  // 进入页面便设置富文本中的内容
  editContent(){
    const that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
      var html = `<p>你好呀之华</p><p><img src="https://profile.csdnimg.cn/7/2/3/2_qq_36789311" width="100%" data-custom="id=abcd&amp;role=god"></p><p><br></p>`;
      that.editorCtx.setContents({
        "html": html,

      })
    }).exec();
    
  }
})

最后显示如下:

小程序的四次元口袋:editor富文本编辑器的使用、渲染,以及rich-text进行解析

 所有的操作记录均已完毕,喜欢请点赞关注,如有不足请予以指正。

相关标签: 微信小程序

上一篇:

下一篇: