Javascript 聚焦/单击时选择 contenteditable div 中的所有文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3805852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:13:21  来源:igfitidea点击:

select all text in contenteditable div when it focus/click

javascriptjquery

提问by angry kiwi

I've got contenteditable div as below.

我有如下内容可编辑的 div。

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

What I need is, when I click on the div, all the text will automatically get selected. Can you give me solution please?

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

回答by Tim Down

This will do it. The timer is there for Chrome and Safari because in those browsers, the native browser behaviour that selects the whole element seems to trigger after the focus event, thereby overriding the effect of the selection code unless postponed until after the focus event:

这将做到。计时器适用于 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);
};

回答by Danylo Mysak

Try this:

尝试这个:

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

回答by Supreme Dolphin

The problem with focusevent on a divis that it can't fire because it thinks a divshould not be editable. Editable contents in the DOM are marked with tabindexin the background, so in order for your div to receive the onfocusevent, you need to explicitly declare the div's tabindexproperty. HTML:

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>

That should work with onfocus.

那应该与onfocus.