除了Tim Downs的答案,我提出了一个即使在oldIE中也可以使用的解决方案:
var selectText = function() {
var range, selection;
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(this);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();
selection.addRange(range);
}
};
document.getElementById('foo').ondblclick = selectText;
在IE 8 +,Firefox 3 +,Opera 9+和Chrome 2+中进行了测试。甚至我已经将其设置为jQuery插件:
jQuery.fn.selectText = function() {
var range, selection;
return this.each(function() {
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(this);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();
selection.addRange(range);
}
});
};
$('#foo').on('dblclick', function() {
$(this).selectText();
});
...以及谁参加了比赛,所有速食咖啡都一样:
jQuery.fn.selectText = ->
@each ->
if document.body.createTextRange
range = document.body.createTextRange()
range.moveToElementText @
range.select()
else if window.getSelection
selection = window.getSelection()
range = document.createRange()
range.selectNodeContents @
selection.removeAllRanges()
selection.addRange range
return
更新:
如果要选择整个页面或可编辑区域的内容(带有标记contentEditable
),则可以切换到designMode
并使用,以简化操作document.execCommand
:
在MDN上有一个很好的起点,并提供了一些文档。
var selectText = function () {
document.execCommand('selectAll', false, null);
};
(在IE6 +,Opera 9 +,Firefoy 3 +,Chrome 2+中运行良好)http://caniuse.com/#search=execCommand
selectElementContents()
一个setTimeout()
或requestAnimationFrame()
如果从一个叫onfocus
。参见jsfiddle.net/rudiedirkx/MgASG/1/show