<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div contenteditable="true" oninput="say()"
id="box"
style="height:100px;margin-top: 200px">
</div>
<button onclick="insert()">点击插入图片</button>
</body>
<script>
let say = ()=>{
let selection =window.getSelection()
let str = selection.focusNode
let box =document.getElementById('box')
// console.dir(box.innerHTML)
// alert(str)
// alert('oninput 1')
}
let box = document.getElementById('box')
let insert =()=>{
let imgEle = document.createElement('img')
imgEle.style.width='10px'
imgEle.style.height='10px'
imgEle.style.background='red'
box.focus()
showHtml()
let lastSelect= null
let selection =window.getSelection()
let range = selection.getRangeAt(0)
box.onblur = function(){
lastSelect = range
}
if(lastSelect){
alert('lastSelect')
// lastSelect.insertNode(imgEle)
// lastSelect.setStartAfter(imgEle)
}else{
range.insertNode(imgEle)
range.setStartAfter(imgEle)
}
}
let showHtml = ()=>{
alert(' show html')
let box =document.getElementById('box')
let pre =null
pre =box.innerHTML
// alert(pre.length)
if(pre){
// alert(pre.length)
if(pre.length > box.innerHTML.length){
alert('删除')
}else{
alert('增加')
}
}
console.log(box.innerHTML)
}
</script>
</html>
失去焦点前光标位置
输入框里失去焦点后插入后 光标跑前面去了 这种情况怎么存储上次的正确的range对象?