微信小程序 富文本编辑器 editor

完整微信小程序(Java后端) 技术贴目录清单页面(必看)

富文本编辑器,可以对图片、文字进行编辑。

编辑器导出内容支持带标签的 html和纯文本的 text,编辑器内部采用 delta 格式进行存储。

通过setContents接口设置内容时,解析插入的 html 可能会由于一些非法标签导致解析错误,建议开发者在小程序内使用时通过 delta 进行插入。

富文本组件内部引入了一些基本的样式使得内容可以正确的展示,开发时可以进行覆盖。需要注意的是,在其它组件或环境中使用富文本组件导出的html时,需要额外引入,并维护<ql-container><ql-editor></ql-editor></ql-container>的结构。

图片控件仅初始化时设置有效。

相关 api:EditorContext

属性类型默认值必填说明最低版本
read-onlybooleanfalse设置编辑器为只读2.7.0
placeholderstring提示信息2.7.0
show-img-sizebooleanfalse点击图片时显示图片大小控件2.7.0
show-img-toolbarbooleanfalse点击图片时显示工具栏控件2.7.0
show-img-resizebooleanfalse点击图片时显示修改尺寸控件2.7.0
bindreadyeventhandle编辑器初始化完成时触发2.7.0
bindfocuseventhandle编辑器聚焦时触发,event.detail = {html, text, delta}2.7.0
bindblureventhandle编辑器失去焦点时触发,detail = {html, text, delta}2.7.0
bindinputeventhandle编辑器内容改变时触发,detail = {html, text, delta}2.7.0
bindstatuschangeeventhandle通过 Context 方法改变编辑器内样式时触发,返回选区已设置的样式2.7.0

编辑器内支持部分 HTML 标签和内联样式,不支持classid

支持的标签

不满足的标签会被忽略,<div>会被转行为<p>储存。

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

支持的内联样式

内联样式仅能设置在行内元素或块级元素上,不能同时设置。例如 font-size 归类为行内元素属性,在 p 标签上设置是无效的。

类型样式
块级样式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

Bug & Tip

  1. tip: 使用 catchtouchend 绑定事件则不会使编辑器失去焦点(2.8.3)
  2. tip: 插入的 html 中事件绑定会被移除
  3. tip: formats 中的 color 属性会统一以 hex 格式返回
  4. tip: 粘贴时仅纯文本内容会被拷贝进编辑器
  5. tip: 插入 html 到编辑器内时,编辑器会删除一些不必要的标签,以保证内容的统一。例如<p><span>xxx</span></p>会改写为<p>xxx</p>
  6. tip: 编辑器聚焦时页面会被上推,系统行为以保证编辑区可见

示例代码

在开发者工具中预览效果

editor.wxml

<view class="container" style="height:{{editorHeight}}px;">
  <editor id="editor" class="ql-container" placeholder="{{placeholder}}" bindstatuschange="onStatusChange" bindready="onEditorReady">
  </editor>
</view>

<view class="toolbar" catchtouchend="format" hidden="{{keyboardHeight > 0 ? false : true}}" style="bottom: {{isIOS ? keyboardHeight : 0}}px">
  <i class="iconfont icon-charutupian" catchtouchend="insertImage"></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-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--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>
</view>

editor.js

Page({
  data: {
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad() {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  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() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '80%',
          success: function () {
            console.log('insert image success')
          }
        })
      }
    })
  }
})

editor.json

{
  "navigationBarTitleText": "发表文章",
  "disableScroll": true
}

editor.wxss

@import "../common/lib/weui.wxss";
@import "./assets/iconfont.wxss"

.container {
  position: absolute; 
  top: 0; 
  left: 0; 
  width: 100%;
}

.ql-container {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  font-size: 16px;
  line-height: 1.5;
  overflow: auto;
  padding: 10px 10px 20px 10px;
  border: 1px solid #ECECEC;
}

.ql-active {
  color: #22C704;
}

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

.toolbar {
  box-sizing: border-box;
  padding: 0 10px;
  height: 50px;
  width: 100%;
  position: fixed;
  left: 0;
  right: 100%;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #ECECEC;
  border-left: none;
  border-right: none;
}


运行效果(请用真机调试):

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tAue7eNg-1622196446094)(image-20210528104114369.png)]

微信搜一搜【java1234】关注这个放荡不羁的程序员,关注后回复【资料】有我准备的一线大厂笔试面试资料以及简历模板。

  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值