Maybe I'm misreading the question, but wouldn't the following do (assuming an editable <div>
with id "editable")? The timer is there because in Chrome, 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);
range.collapse(true);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(div);
range.collapse(true);
range.select();
}
}, 1);
};
div.focus();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…