功能要求
- 1.标签与文本同时存在的输入框
- 2.对文本内容,进行指定格式提取
- 3.任意位置添加标签与文本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.edit {
height: 500px;
width: 500px;
border: 1px solid red;
}
.tableSpan{
background-color: red;
margin: 2px;
}
</style>
</head>
<body>
<div
class="edit"
id="inputContent"
contenteditable="true"
placeholder="请在这输入内容"
onblur="blurEdit()">
</div>
<div>
<h3>标签列表</h3>
</div>
<div>
<span class="tableSpan" onclick="tableOnclick(0)">距离</span>
<span class="tableSpan" onclick="tableOnclick(1)">距离1</span>
<span class="tableSpan" onclick="tableOnclick(2)">距离2</span>
<span class="tableSpan" onclick="tableOnclick(3)">距离3</span>
<span class="tableSpan" onclick="tableOnclick(4)">距离4</span>
<span class="tableSpan" onclick="tableOnclick(5)">距离5</span>
<span class="tableSpan" onclick="tableOnclick(6)">距离6</span>
<span class="tableSpan" onclick="tableOnclick(7)">距离7</span>
<span class="tableSpan" onclick="tableOnclick(8)">距离8</span>
<span class="tableSpan" onclick="tableOnclick(9)">距离9</span>
</div>
<div>
<button onclick="toInfo()">生成最后报文</button>
</div>
<textarea id="info"></textarea>
<script>
var tableArray = [
{
"value":"距离",
"code":"aa"
},
{
"value":"距离1",
"code":"bb"
},
{
"value":"距离2",
"code":"cc"
},
{
"value":"距离3",
"code":"dd"
},
{
"value":"距离4",
"code":"ee"
},
{
"value":"距离5",
"code":"ff"
},
{
"value":"距离6",
"code":"gg"
},
{
"value":"距离7",
"code":"hh"
},
{
"value":"距离8",
"code":"jj"
}
];
let position = ''
function blurEdit() {
position = window.getSelection().getRangeAt(0)
}
function tableOnclick(index) {
var tableName = tableArray[index].value;
if(position === ''){
const div = document.getElementById('inputContent')
div.focus()
const range = window.getSelection()
range.selectAllChildren(div)
range.collapseToEnd()
position = window.getSelection().getRangeAt(0)
}
const span = document.createElement('span')
var tableId = "table"+index;
span.innerHTML = '<span contenteditable="false" id="'+tableId+'" class="tableSpan" onClick="deleteTable('+index+')">'+tableName+'</span>'
position.insertNode(span.firstChild)
}
function deleteTable(index){
var tableSpanNode = document.getElementById( "table"+index);
tableSpanNode.remove();
}
function toInfo(){
var infoText = document.getElementById("info");
var textInfo = "";
const div = document.getElementById('inputContent')
var childNodeArray = div.childNodes;
for(var i =0;i<childNodeArray.length;i++){
console.log("节点",childNodeArray[i]);
var child = childNodeArray[i];
if(child.nodeName == "#text"){
var text = child.data.replace("\n","").replace(/\s/g, '');
textInfo += text;
}else if(child.nodeName == "SPAN"){
var index = child.id.replace("table","");
var code = tableArray[index].code;
textInfo += code;
}
}
infoText.value = textInfo;
}
</script>
</body>
</html>