除了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