Vue 自定义编辑器 contenteditable

效果图如下:
在这里插入图片描述

html


<div ref="edition" class="edition">
  <div
    ref="contentInput"
    :contenteditable="true"
    placeholder="请输入幕文本"
    class="content-input"
    @input="onChange"
    v-html="screenValue"
  />
</div>
<div class="actions">
  <el-button
    type="text"
    size="mini"
    round
    @click="insertContent"
  >
    连续
  </el-button>
  <el-button
    type="text"
    size="mini"
    round
    @click="insert(0.5)"
    v-text="'0.5s'"
  />
  <el-button
    type="text"
    size="mini"
    round
    @click="insert(1.0)"
    v-text="'1s'"
  />
  <el-button
    type="text"
    size="mini"
    round
    @click="insert(2.0)"
    v-text="'2s'"
  />
</div>

相关方法:

name: 'ScreenEditor',
model: {
  prop: 'screen',
  event: 'change',
},
props: {
  index: {
    type: Number,
    default: 0,
  },
  screen: {
    type: Object,
    default: () => ({ valueText: '' }),
  },
},
data() {
  return {
    screenValue: this.screen.valueText,
  };
},
watch: {
  screen(newValue) {
    this.screenValue = newValue.valueText;
    this.formatText();
  },
  sensitiveWords: {
    handler(wordsList) {
      // 处理敏感词
      wordsList.forEach(({ context }) => {
        const span = `<span class="sensitive" contenteditable="false">${context}</span>`;
        if (!this.screenValue.includes(span)) {
          this.screenValue = this.screenValue.replace(context, span);
        }
        this.$emit('change', { value: this.screenValue, index: this.index });
      });
    },
    immediate: true,
    deep: true,
  },
},
created() {
 this.formatText();
  // 聚焦 
  this.$refs.contentInput.focus();
  const range = getSelection();
  range.selectAllChildren(this.$refs.contentInput);
  range.collapseToEnd();
},
methods: {
  formatText() {
    if (this.screen.valueText) {
      let text = this.screen.valueText.replace('[0.5]', this.getSpan('pause', 0.5).outerHTML);
      text = text.replace('[1.0]', this.getSpan('pause', 1).outerHTML);
      text = text.replace('[2.0]', this.getSpan('pause', 2).outerHTML);
      const continueArr = text.match(/\[(.+?)\]/g);
      continueArr?.forEach((item) => {
        text = text.replace(item, this.getSpan('continue', item.replace(/\[(.+?)\]/g, '$1')).outerHTML);
      });
      this.screenValue = text;

      this.$nextTick(() => {
        this.addContinueLabel();
      });
    }
  },
  onChange(e) {
    this.$emit('change', { value: e.target.innerHTML, index: this.index });
  },
  getRange() {
    const selection = getSelection();
    if (selection.getRangeAt > 0) {
      return { range: selection.getRangeAt(0), selection };
    }

    const range = document.createRange();
    range.setStart(selection.anchorNode, selection.anchorOffset);
    range.setEnd(selection.focusNode, selection.focusOffset);
    return { range, selection };
  },
  getSpan(className, text) {
    const span = document.createElement('span');
    span.className = className;
    if (className === 'continue') {
      span.setAttribute('text', text);
      span.innerText = text;
    } else {
      span.innerText = `${Number(text).toFixed(1)}s`;
      span.setAttribute('second', Number(text).toFixed(1));
      span.setAttribute('contenteditable', 'false');
      return span;
    }

    return span;
  },
  insert(num) {
    const { range } = this.getRange();
    const span = this.getSpan('pause', num);
    range.insertNode(span);
    this.$emit('change', { value: this.$refs.contentInput.innerHTML, index: this.index });
  },
  insertContent() {
    const { range, selection } = this.getRange();
    if (!selection.toString().trim()) {
      return;
    }
    const span = this.getSpan('continue', selection.toString());
    range.deleteContents();
    range.insertNode(span);
    this.addContinueLabel();
  },
  addContinueLabel() {
    this.$refs.contentInput.querySelectorAll('.continue').forEach((item) => {
      const id = `#l${item.id.slice(1)}`;
      if (!document.querySelector(id)) {
        const continueLabel = document.createElement('div');
        continueLabel.className = 'continue-label';
        continueLabel.innerHTML = '\n<div class="val" val="letter">\n<button id="detail">连续</button>\n<button id="del" class="el-icon-circle-close" />\n</div>\n';
        const randomId = (new Date()).getTime() + Math.floor(1e3 * Math.random());
        continueLabel.id = `l${randomId}`;
        item.id = `p${randomId}`;
        continueLabel.querySelector('#del').addEventListener('click', () => {
          const continueSpan = document.querySelector(`#p${randomId}`);
          continueSpan && (continueSpan.outerHTML = continueSpan.innerHTML);
          continueLabel.remove();
          this.$emit('change', { value: this.$refs.contentInput.innerHTML, index: this.index });
        });
        this.$refs.edition.append(continueLabel);
      }
    });
    this.$refs.contentInput.querySelectorAll('.continue').forEach((item) => {
      const id = `#l${item.id.slice(1)}`;
      const span = document.querySelector(id);
      if (span) {
        if (Number(item.offsetTop) === 0 && Number(item.offsetLeft) === 0) {
          span.remove();
        } else {
          span.style.top = `${-20 + item.offsetTop}px`;
          span.style.left = `${item.offsetLeft}px`;
        }
      }
    });
    this.$emit('change', { value: this.$refs.contentInput.innerHTML, index: this.index });
  },
},
<style lang="scss" scoped>
.content {
  position: relative;

  .content-input {
    width: 100%;
  	min-height: 408px !important;
    padding: 20px 15px;
    background-image: none;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    line-height: 40px;
    color: #333333;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    -webkit-user-modify: read-write-plaintext-only;

    &:empty:before {
      content: attr(placeholder);
      font-size: 13px;
      color: #999;
    }

    &:focus:before {
      content: none;
    }
  }
}
</style>

<style lang="scss">
.edition {
  .content-input {
    .pause {
      background-color: rgba(42, 139, 240, 0.2);
      white-space: nowrap;
      color: #308FF1;
      border-radius: 4px;
    }

    .continue {
      line-height: 40px;
      border-bottom: solid 1px #308FF1;
      border-left: solid 1px #308FF1;
    }

    .sensitive {
      color: rgb(202, 63, 68);
      text-decoration: underline;
    }
  }

  .continue-label {
    position: absolute;
    font-size: 14px;
    background-color: rgba(40, 133, 229, 0.2);
    color: #308FF1;
    border-radius: 2px 2x 2px 0;
    display: flex;
    align-items: center;

    #detail {
      display: inline-flex;
      padding: 0 2px;
      border: none;
      background: none;
      outline: none;
      color: #308FF1;
      transition: 0.1s;
    }

    #del {
      cursor: pointer;
      display: inline-flex;
      border: none;
      background: none;
      outline: none;
      color: #308FF1;
      transition: 0.1s;
    }
  }
}
</style>

使用时对内容进行format

const div = document.createElement('div');
div.innerHTML = screen.valueText;
const sensitive = div.querySelectorAll('.sensitive');
Array.from(sensitive).forEach((e) => {
  e.outerHTML = e.innerText;
});
const pause = div.querySelectorAll('.pause');
Array.from(pause).forEach((e) => {
  e.outerHTML = `[${e.innerText.replace('s', '')}]`;
});
const continueSpan = div.querySelectorAll('.continue');
Array.from(continueSpan).forEach((e) => {
  e.outerHTML = `[${e.innerText}]`;
});
screen.valueText = div.innerText;
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值