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