我在我的代码中使用了一个contenteditable元素,其中文本变成了emojis。例如,abc :)
应变为abc
。但是,在图像出现在contenteditable中之后,光标会移回到可竞争对象的开头,然后整个代码停止工作。
这是我正在使用的代码:
var data = {
"value": ":)",
"image": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSaW1KOeceO85Y7KfUXGyLZm1LfTwjhQspKKXUl3D3a5Mo1uz-AhA"
};
$(document).ready(function() {
document.body.onkeyup = function(e) {
if (e.keyCode == 32) {
//alert("space bar");
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
var word = getWord(text);
console.log(word);
console.log(data.value);
if (word.includes(data.value)) {
//alert("true");
var img = "<img id='image' src='" + data.image + "' class='image' /> ";
console.log(img);
$("#text-box").html(function(_, html) {
return html.replace(data.value, img);
}); //[0].setSelectionRange($("#text-box").html().length, $("#text-box").html().length);
var el = document.getElementById("image");
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[2], 2);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
function getWord(text) {
var word = text.split(" ").pop();
return word;
}
}
});
&#13;
.image {
position: relative;
max-height: 1.4em;
max-width: 1.4em;
}
[contenteditable] {
-webkit-appearance: textfield;
appearance: textfield;
border: 1px solid black;
line-height: 1.4em;
min-height: 20px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id='text-box'>
</div>
&#13;
这是我的Codepen的链接: Link