在焦点/单击时选择contenteditable div中的所有文本

ang*_*iwi 23 javascript jquery

我有满足感的div如下所示.

<div style=" border:solid 1px #D31444" contenteditable="true">12 some text...</div>
Run Code Online (Sandbox Code Playgroud)

我需要的是,当我点击div时,所有文本将自动被选中.你能给我解决方案吗?

Tim*_*own 42

这样做.计时器适用于Chrome和Safari,因为在这些浏览器中,选择整个元素的本机浏览器行为似乎在焦点事件后触发,从而覆盖选择代码的效果,除非推迟到焦点事件之后:

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);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(div);
            range.select();
        }
    }, 1);
};
Run Code Online (Sandbox Code Playgroud)

  • @Jonz:`window.getSelection()`和`document.createRange()`,它们现在都是标准化的,在大多数浏览器中都支持,但不支持IE <9.IE确实有自己的选择/范围API,通过此处访问`document.body.createTextRange()`. (3认同)

Dan*_*sak 39

试试这个:

<div style="border:solid 1px #D31444"
     contenteditable="true"
     onclick="document.execCommand('selectAll',false,null)">12 some text...</div>
Run Code Online (Sandbox Code Playgroud)

  • 使用`focus`事件可以做得更好,因为只要用户尝试单击以放置插入符,使用click事件就会突出显示所有内容. (8认同)
  • http://jsfiddle.net/rudiedirkx/MgASG/1/show/可能有帮助吗? (4认同)
  • 当用户使用"Tab"键导航到contenteditable div时,这不起作用. (4认同)
  • 嗯,可能,但这取决于问题的作者想要什么。 (2认同)
  • 我刚刚在Chrome版本24.0.1312.57 OS X中试过这个.使用jQuery 1.9.1,绑定到`focus` _does not_ work.绑定到`click`事件确实选择了文本:`$('.editable').on('click',function(){document.execCommand('selectAll',false,null);});` (2认同)

Sup*_*hin 6

focusa 上的事件的问题div在于它无法触发,因为它认为 adiv不应该是可编辑的。DOM 中的可编辑内容在tabindex后台标记为,因此为了让您的 div 接收onfocus事件,您需要显式声明divtabindex属性。HTML:

<div style=" border:solid 1px #D31444" contenteditable="true" tabindex="1" onfocus="document.execCommand('selectAll',false,null)" >12 some text...</div>
Run Code Online (Sandbox Code Playgroud)

那应该与onfocus.

  • 这样做会导致它选择整个文档。您可以使用相同的代码,但我建议对 `150` 毫秒使用 `setTimeout`,这样它就不会选择整个文档。希望这对大家有帮助! (2认同)