需求:点击上面的按钮可以显示在文本框,并且光标放在某个位置,删除的时候可以直接删除整体,比如放在本金的哪里,可以直接删除本金两个字。
实现代码如下:
//vue 完整代码
<template>
<div>
<el-form>
<el-form-item label="按钮" :label-width="formLabelWidth">
<template v-for="logicSymbol in logicSymbols">
<el-button
type="blue"
size="small"
:key="`${logicSymbol.itemCode}`"
@click="HandelClick(logicSymbol.itemName)"
>{{ logicSymbol.itemName }}</el-button
>
</template>
</el-form-item>
<el-form-item label="公式" :label-width="formLabelWidth">
<div
style="margin-left:30px;border: 1px solid red"
ref="dialogTxtCon"
id="dialogTxtCon"
contentEditable="true"
v-html="htmlText"
@blur="textHtmlChanged"
/>
</el-form-item>
<el-button type="blue" size="small" @click="btnHandelClick()"
>确定</el-button
>
</el-form>
</div>
</template>
<script>
export default {
props: {
date: {
type: String,
default: function () {
return "";
},
},
name: {
type: String,
default: function () {
return "";
},
},
province: {
type: String,
default: function () {
return "";
},
},
},
data() {
return {
input:'',
formLabelWidth: "240",
logicSymbols: [
{
itemName: "本金",
itemCode: "1",
},
{
itemName: "年利率",
itemCode: "2",
},
{
itemName: "利润",
itemCode: "3",
},
{
itemName: "计算规则1",
itemCode: "4",
},
],
htmlText: '',
};
},
components: {},
computed: {},
mounted() {},
methods: {
HandelClick(str) {
const html = ` <span contentEditable="false"> ${str} </span> `
this.$refs.dialogTxtCon.focus(); // focus 输入框,否则会跟随光标追加 html
const sel = window.getSelection();
// Selection 选区对象,表示用户选择的文本范围或光标的当前位置
if (sel.getRangeAt && sel.rangeCount) {
let range = sel.getRangeAt(0); // 包含当前选区内容的区域对象
range.deleteContents(); // Range.deleteContents(): 移除来自 Document 的 Range 内容
const el = document.createElement("div"); // 生成一个 div
el.innerHTML = html; // div 里的内容为上面定义的要添加的元素
const frag = document.createDocumentFragment();
let node, lastNode;
while ((node = el.firstChild)) {
// 把生成 div 里的内容,即 html,移到 frag 里
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
},
btnHandelClick() {
let innerText = document.getElementById("dialogTxtCon").innerText;
let innerHTML = document.getElementById("dialogTxtCon").innerHTML;
console.log(innerText);
console.log(innerHTML);
},
textHtmlChanged(e) {
// console.log(e)
// this.htmlText = e.target.innerHTML;
},
},
destroyed() {
console.log("reuseChild destroyed");
},
};
</script>
网友评论