点击按钮根据光标位置插入内容

一. 最终实现效果如下如所示
请添加图片描述

二. 实现代码

<template>
  <div
    ref="selectionRef1"
    id="selection-container"
    class="selection-container"
    contenteditable="true"
    >请在此处输入内容</div
  >
  <div
    ref="selectionRef2"
    id="selection-container2"
    class="selection-container selection-container-box"
    contenteditable="true"
    >第二个输入地区</div
  >
  <button class="btn" @click="handleOneFn">插入文案1</button>
  <button class="btn" @click="handleTwoFn">插入文案2</button>
  <button @click="handleGetOne">获取内容1</button>
  <button @click="handleGetTwo">获取内容2</button>
</template>
<script>
  import { ref } from 'vue';
  import SelectionFn from './selection';
  export default {
    setup() {
      const selectionRef1 = ref(null);
      const selectionRef2 = ref(null);
      const { handleToLast: handleOneFn, handleGetContent: handleGetOne } = SelectionFn(
        selectionRef1,
        '#插入文案1#',
      );
      const { handleToLast: handleTwoFn, handleGetContent: handleGetTwo } = SelectionFn(
        selectionRef2,
        '#插入文案2#',
      );
      return {
        selectionRef1,
        selectionRef2,
        handleOneFn,
        handleTwoFn,
        handleGetOne,
        handleGetTwo,
      };
    },
  };
</script>
<style lang="less" scoped>
  .selection-container {
    width: 300px;
    height: 100px;
    overflow: auto;
    background: #ddd;

    &-box {
      background: pink;
    }
  }

  .btn {
    width: 100px;
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #ccc;
  }
</style>
<style>
  .insert-text {
    color: red;
    cursor: initial;
  }

  .insert-text:hover {
    color: red;
  }
</style>

selection.js代码

const useSelection = (currentRef, insertText) => {
  return {
    handleToLast: () => {
      currentRef.value.focus();
      const sel = window.getSelection();
      if (!sel.anchorNode) {
        currentRef.value.focus();
      }
      const range = sel.getRangeAt(0);
      const str = '<a href="#" class="insert-text">' + insertText + '</a>';
      const hasR = range.createContextualFragment(str);
      range.insertNode(hasR);
      sel.removeAllRanges();
      sel.addRange(range);
      range.collapse(false);
    },

    handleGetContent: () => {
      const res = currentRef.value.innerHTML;
      console.log('res,', res);
    },
  };
};

export default useSelection;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值