微信小程序editor富文本编辑

2020-12-08 10:10:39 浏览数 (1)

直接复制看效果

代码语言:javascript复制
<editor class="editor" id="editor" show-img-toolbar show-img-resize value="{{content}}" placeholder="请输入"
  bindready="readyEditor" bindstatuschange="changeEditor" bindinput="inputEditor">
</editor>

<view class="toolbar" catchtouchend="formatOpt">
  <view catchtouchend="insertImage">上传图片</view>
  <view class="{{formats.bold ? 'active' : ''}}" data-name="bold">加粗</view>
  <view class="{{formats.list=='unchecked' ? 'active' : ''}}" data-name="list" data-value="check">清单</view>
  <view class="{{formats.list=='ordered' ? 'active' : ''}}" data-name="list" data-value="ordered">列表</view>
  <view class="{{formats.align=='center' ? 'active' : ''}}" data-name="align" data-value="center">居中</view>
</view>
代码语言:javascript复制
.editor {
  width: 100%;
  height: calc(100vh - 100rpx);
}

.toolbar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 2rpx solid #ECECEC;
  background: #fff;
  z-index: 1;
}

.toolbar view {
  font-size: 24rpx;
}

.active {
  font-weight: 600;
  color: cadetblue;
}
代码语言:javascript复制
Page({
  data: {
    formats: {},
    content: "<p>公众号关注:wePanda</p>"
  },
  onLoad: function () {},

  // editor初始化
  readyEditor() {
    wx.createSelectorQuery().select('#editor').context((res) => {
      this.editorCtx = res.context
      this.editorCtx.setContents({
        html: this.data.content
      });
    }).exec()
  },

  //配置选项 
  formatOpt(e) {
    let {
      name,
      value
    } = e.target.dataset
    this.editorCtx.format(name, value)
  },

  // 上传图片
  insertImage() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        this.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          width: '80%'
        })
      }
    })
  },

  // 内容格式
  changeEditor(e) {
    this.setData({
      formats: e.detail
    })
    console.log(this.data.formats)
  },

  // 监听输入内容
  inputEditor(e) {
    this.setData({
      content: e.detail.html
    })
    console.log(e.detail.html)
  }
})

0 人点赞