console
function addImg() {
let input = document.getElementById('inputRef')
input.innerHTML += '<img src="https://fe.ecool.fun/static/leibusi.ac7fa5ed.jpeg" />'
input.focus()
keepLastIndex(input)
}
function keepLastIndex(obj) {
if (window.getSelection) {
obj.focus();
var range = window.getSelection();
range.selectAllChildren(obj);
range.collapseToEnd();
}
else if (document.selection) {
var range = document.selection.createRange();
range.moveToElementText(obj);
range.collapse(false);
range.select();
}
}
<div class="inputDiv" contenteditable="true" id="inputRef"></div>
<button onclick="addImg()">添加表情</button>
.inputDiv{
border: 1px solid #ccc;
min-height: 30px;
height: auto;
background: #fff;
padding: 8px;
line-height: 30px;
vertical-align: middle;
}
.inputDiv img{
width: 20px;
height: 20px;
margin-bottom: -4px;
}