greasemonkey - 选择文本后如何调用函数

标签 greasemonkey getselection

我想在文档中选择文本后调用函数。以下代码无效

var showSelWin = document.getElementById('innerwindow');
var txt = ' ';
if (document.getSelection) function(){
txt = document.getSelection();
showSelWin.innerHTML = txt;
document.body.insertBefore(showSelWin, document.body.firstChild);}

最佳答案

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 方法和 window.getSelection 方法返回的 selectionRange 对象的 toString 方法来获取选择的文本内容。

在旧的 Internet Explorer 版本中,使用选择对象的 createRange 方法和 createRange 方法返回的 TextRange 对象的文本属性来获取选择的文本内容。

为您提供的工作示例: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);
        }
    }
}

关于greasemonkey - 选择文本后如何调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9172056/

相关文章:

javascript - getSelection() 可以只应用于某个元素(而不是整个文档)吗?

javascript - 我希望我的输入写在左边

javascript - 使用 Javascript 进行图像处理?

javascript - 修改Google搜索结果页面

javascript - 使用 Javascript 将 iframe 插入 Div - 适用于 Greasemonkey

javascript - 如何使用 javascript 在 getSelection() 中查找所选文本的索引?

java - 如何获取 JList 中的选定项并使用转换

javascript - 如何使用javascript获取选定的html文本?

javascript - 使用 greasemonkey 和/或 gmail API 来减少邮件 Pane 的宽度

javascript - 如何在textarea中使用keydown事件?