代码之家  ›  专栏  ›  技术社区  ›  angry kiwi

选中contenteditable div中的所有文本(当它聚焦/单击[复制]时)

  •  23
  • angry kiwi  · 技术社区  · 14 年前

    我有如下可编辑的div。

    <div style=" border:solid 1px #D31444" contenteditable="true">12 some text...</div>
    

    3 回复  |  直到 14 年前
        1
  •  50
  •   Alexis Wilke    6 年前

    试试这个:

    <div style="border:solid 1px #D31444"
         contenteditable="true"
         onclick="document.execCommand('selectAll',false,null)">12 some text...</div>
    
        2
  •  53
  •   Tim Down    14 年前

    这样就可以了。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);
    };
    
        3
  •  6
  •   Supreme Dolphin    9 年前

    问题在于 focus 事件 div 它不能开火是因为它认为 部门 tabindex onfocus 事件,则需要显式声明 部门 TAB顺序 HTML格式:

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

    这应该和