检索选定的单词
Retrieving a word that is selected
我正在编写一个插件,试图在firefox浏览器中显示所选单词的含义。如何捕获所选单词?
我使用下面的函数来获取附加组件中的选定文本。使用的方法取决于选择的位置和Firefox的版本。虽然可以根据这些标准选择要使用的方法,但在我编写/调整它时(然后在Firefox 31.0中崩溃时更新它),只需运行多个方法直到获得有效字符串更容易。
/**
* Account for an issue with Firefox that it does not return the text from a selection
* if the selected text is in an INPUT/textbox.
*
* Inputs:
* win The current window element
* doc The current document
* These two items are inputs so this function can be used from
* environments where the variables window and document are not defined.
*/
function getSelectedText(win,doc) {
//Adapted from a post by jscher2000 at
// http://forums.mozillazine.org/viewtopic.php?f=25&t=2268557
//Is supposed to solve the issue of Firefox not getting the text of a selection
// when it is in a textarea/input/textbox.
var ta;
if (win.getSelection && doc.activeElement) {
if (doc.activeElement.nodeName == "TEXTAREA" ||
(doc.activeElement.nodeName == "INPUT" &&
doc.activeElement.getAttribute("type").toLowerCase() == "text")
){
ta = doc.activeElement;
return ta.value.substring(ta.selectionStart, ta.selectionEnd);
} else {
//As of Firefox 31.0 this appears to have changed, again.
//Try multiple methods to cover bases with different versions of Firefox.
let returnValue = "";
if (typeof win.getSelection === "function") {
returnValue = win.getSelection().toString();
if(typeof returnValue === "string" && returnValue.length >0) {
return returnValue
}
}
if (typeof doc.getSelection === "function") {
returnValue = win.getSelection().toString();
if(typeof returnValue === "string" && returnValue.length >0) {
return returnValue
}
}
if (typeof win.content.getSelection === "function") {
returnValue = win.content.getSelection().toString();
if(typeof returnValue === "string" && returnValue.length >0) {
return returnValue
}
}
//It appears we did not find any selected text.
return "";
}
} else {
return doc.getSelection().toString();
}
}
相关文章:
- 使用JSP从服务器检索和显示图像
- 通过Magento的网络服务检索运费
- 如何通过php页面将数据库值检索到jquery自动完成框中
- 当鼠标悬停在文本中的单词上时显示警报
- 匹配一个单词,其中候选人可以跨越顺序组(跨度)
- 如何使用jquery强制一个单词更改大小写等以保留品牌
- 拆分单词jquery
- 无法使用javascript检索SPList项
- 可以't使用Angular解析/检索JSON
- 如何让程序检查所选单词中是否有按键
- GoogleFeed正在检索图像
- 通过ajax将坐标传递到php服务器端,并在处理后检索到javascript
- 使用Scala Play Framework视图中的键检索映射值
- 如何在悬停时流畅地更改单词
- 检索选定的单词
- 缺少单词/编号.xml在 OOXML 中使用 JavaScript 检索 bodyOOXML.value 时
- 如何从字符串中检索单词
- 正在从UIWebView检索最接近点的单词
- 从javascript中检索后,在PHP数组中只返回1个字符而不是整个单词
- 单击按钮可从文本区域检索高亮显示的单词