问题的旧版本如下,经过更多研究后,我决定重新表述问题。和以前一样,问题是,我需要在不突出显示文本的情况下聚焦 contenteditable div,在 Chrome 中直接聚焦会突出显示文本。
我意识到人们通过重置文本区域中的插入符位置来解决文本区域中的这个问题。我如何使用 contenteditable 元素来做到这一点?我尝试过的所有插件仅适用于文本区域。谢谢。
问题的旧措辞:
I have a contenteditable element that I want to focus, but only insofar as to place the cursor at the front of the element, rather selecting everything.
elem.trigger('focus');
with jquery selects all the text in the entire element in chrome. Firefox behaves correctly, setting the caret at the front of the text. How can I get Chrome to behave the way I want, or is focus perhaps not what I'm looking for.
谢谢大家。
最佳答案
也许我误读了这个问题,但是下面的代码不行吗(假设可编辑 <div>
的 id 为“editable”)?计时器之所以存在,是因为在 Chrome 中,选择整个元素的 native 浏览器行为似乎是在 focus
之后触发的。事件,从而覆盖选择代码的效果,除非推迟到焦点事件之后:
var div = document.getElementById("editable");
div.onfocus = function() {
window.setTimeout(function() {
var sel, range;
if (window.getSelection && document.createRange) {
range = document.createRange();
range.selectNodeContents(div);
range.collapse(true);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(div);
range.collapse(true);
range.select();
}
}, 1);
};
div.focus();
关于jquery 在 contenteditable div 中设置光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871081/