为了完整起见,这里是两个答案的更完整版本,包装为 jquery 插件。该插件支持所有主流浏览器。
(它在 coffescript 中,对于 js 代码,前往js2coffee)
$.fn.selectText = () ->
@each ->
text = this
# FF, Chrome, IE9+, and hopefully Opera
if document.createRange? and window.getSelection?
selection = window.getSelection()
range = document.createRange()
range.selectNodeContents text
selection.removeAllRanges()
selection.addRange range
# <= IE8
else if document.body.createTextRange?
range = document.body.createTextRange()
range.moveToElementText text
range.select()
# Safari
else if window.getSelection?
selection = window.getSelection()
selection.setBaseAndExtent text, 0, text, 1