jquery 在 contenteditable div 中设置光标位置

标签 jquery focus contenteditable caret cursor-position

问题的旧版本如下,经过更多研究后,我决定重新表述问题。和以前一样,问题是,我需要在不突出显示文本的情况下聚焦 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/

相关文章:

javascript - JQuery .on ("click", function() ) 不起作用

javascript - 设置搜索字段的默认值 - 请帮忙!

javascript - Jquery 单选按钮提交多次重复相同的值

jquery - 如何在 jquery 中的 if 和 else 中进行数学运算?

javascript - Click-to-focus 和 focus-by-javascript 有什么区别?

python - 当小部件失去焦点时如何拦截

javascript - 只允许在 contentEditable <div> 内移动 <img>

html - contenteditable 中的光标在 Chrome 中无法正常运行

java - 创建Activity时如何使EditText不聚焦

javascript - 如何在 Internet Explorer 中使用 html 子元素获取 contenteditable div 中的插入符位置