gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:03:07 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com