selection.setPosition(container,5); 设置光标位置--到尾端
selection.setPosition(container,0); 设置光标位置--到首端
container 为 编辑容器dom,5 为编辑器子元素的长度,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#app{
300px;
height:100px;
border: 1px solid red;
}
img{
20px;
}
</style>
</head>
<body>
<!--<div contenteditable="true" id="app">
<img src="a.jpg" alt=""> 123
</div>-->
<div contenteditable="true" id="app">
11<img src="a.jpg" alt=""><img src="a.jpg" alt=""> 00 <span class="sp">123</span>
</div>
</body>
<script>
let app = document.querySelector('#app');
app.focus();
let selection = getSelection();
selection.setPosition(app,5);
</script>
</html>
View Code