【问题标题】:how to call function after text is selected选择文本后如何调用函数
【发布时间】:2012-02-07 06:44:16
【问题描述】:
我想在文档中选择文本后调用函数。以下代码不起作用
var showSelWin = document.getElementById('innerwindow');
var txt = ' ';
if (document.getSelection) function(){
txt = document.getSelection();
showSelWin.innerHTML = txt;
document.body.insertBefore(showSelWin, document.body.firstChild);}
【问题讨论】:
标签:
greasemonkey
getselection
【解决方案1】:
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);
}
}
}