I've got contenteditable div as below.
<div style=" bord开发者_Python百科er: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?
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:
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);
};
Try this:
<div style="border:solid 1px #D31444"
contenteditable="true"
onclick="document.execCommand('selectAll',false,null)">12 some text...</div>
Update: Note that document.execCommand
is now deprecated although it still works.
The problem with focus
event on a div
is that it can't fire because it thinks a div
should not be editable. Editable contents in the DOM are marked with tabindex
in the background, so in order for your div to receive the onfocus
event, you need to explicitly declare the div
's tabindex
property.
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
.
精彩评论