一. 最终实现效果如下如所示
二. 实现代码
<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;