除了Tim Downs answer,我还做了一个在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 来简单得多:
有一个很好的starting point at MDN 和a littledocumentation。
var selectText = function () {
document.execCommand('selectAll', false, null);
};
(适用于 IE6+、Opera 9+、Firefoy 3+、Chrome 2+)http://caniuse.com/#search=execCommand