document.getSelection 方法在 Google Chrome、Safari 和 Internet Explorer 中的工作方式与在 Firefox 和 Opera 中不同。
它在 Firefox 和 Opera 中返回一个字符串,在 Google Chrome、Safari 和 Internet Explorer 中返回一个 selectionRange 对象(document.getSelection 方法与 Google Chrome、Safari 和 Internet Explorer 中的 window.getSelection 方法相同)。
在 Firefox、Opera、Google Chrome、Safari 和 Internet Explorer 从版本 9 开始,使用 window.getSelection 方法返回的 selectionRange 对象的 window.getSelection 方法和 toString 方法来获取选择的文本内容。
在较旧的 Internet Explorer 版本中,使用选择对象的 createRange 方法和 createRange 方法返回的 TextRange 对象的 text 属性来获取选择的文本内容。
适合您的工作示例:http: //jsfiddle.net/uX628/
function GetSelectedText () {
if (document.getSelection) { // all browsers, except IE before version 9
var sel = document.getSelection ();
// sel is a string in Firefox and Opera,
// and a selectionRange object in Google Chrome, Safari and IE from version 9
// the alert method displays the result of the toString method of the passed object
alert (sel);
}
else {
if (document.selection) { // Internet Explorer before version 9
var textRange = document.selection.createRange ();
alert (textRange.text);
}
}
}