一个诡异问题折射出我完全不懂js事件
这个问题是通过Stack Overflow 解决的, 下面就是我的提问
this function is not work, but if i set breakpoint in devtools, it will work success, why? so strange……
function insertHtmlAtCursor() {
var range=window.getSelection().getRangeAt(0);
var node = range.createContextualFragment("<div>this is not show</div>");
range.insertNode(node);
}
but if i change code to this, it always run in right way.
var node = document.createTextNode('this is ok.');
i use chrome in macos, here is the demo:
editor.onkeydown=editinput;
function editinput(e) {
if(e.isComposing||e.keyCode===229) {
return;
}
if(e.keyCode==32) {//space
var range=window.getSelection().getRangeAt(0);
var node=range.createContextualFragment('ttttttttttt');
range.insertNode(node);
}
}
<div id="editor" contenteditable="true" class="knowleadge" tabIndex="1">
</div>
this is the demo, when i key in space, it will not insert fragment, but when i debug in chrome, it will insert the fragment.
now thanks @Dekel, i know keyup replace keydown is a solution ,
but because i need deal with tab, and keyup can not really catch the tab key, so i need deal the code in keydown, how can i do it?
and i find settimeout can deal these problem, but is there any other solution? here is the set time out:
if(e.keyCode==32) {//space
setTimeout(dealpace,0);
e.stopPropagation();
e.preventDefault();
}
function dealpace() {
var range=window.getSelection().getRangeAt(0);
var node=range.createContextualFragment('ttttttttttt');
range.insertNode(node);
}
thanks @Dekel, settimeout is not key, the key is e.preventDefault(); like @Dekel say, keydown insert the text, but keyup replace the text with space. so we need e.preventDefault();
like this:
if(e.keyCode==32) {//space
dealpace();
e.stopPropagation();
e.preventDefault();
}
function dealpace() {
var range=window.getSelection().getRangeAt(0);
var node=range.createContextualFragment('ttttttttttt');
range.insertNode(node);
}
原文链接: https://stackoverflow.com/questions/61122797/how-can-i-insert-element-on-caret-by-the-keydown-event