如何检测 contenteditable
中光标之前的单词div 并用其他东西替换它? 这个 works for a textarea
但不适用于此 contenteditable div:
document.getElementById('a').addEventListener('keydown', e => {
if (e.which == 9) {
e.preventDefault();
let endingIndex = e.target.selectionStart; // does not work for contenteditable
let startingIndex = endingIndex && endingIndex - 1;
let value = e.target.innerHTML;
let regex = /[ ]/;
while(startingIndex){
if(regex.test(value[startingIndex])){
++startingIndex;
break;
}
--startingIndex;
}
console.log('word before cursor: ' + value.substring(startingIndex, endingIndex));
}
});
<div contenteditable id="a">Please click here and hit TAB, the word before cursor should be replaced by something else.</div>
最佳答案
这是因为 selectionStart
是仅 HTMLInputElement
的属性。对象的类型。
也许你想看看这个gist或使用Range
直接接口(interface)。
关于javascript - 检测并替换 contenteditable div 上光标之前的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803127/