问题描述
我正在写一个Firefox插件,每当一个单词突出显示时都会触发。然而,我需要一个脚本来检测一个单词突出显示的时间,我被卡住了。一个例子是nytimes.com(当你阅读一篇文章,你突出显示一个字,引用图标弹出)。然而,nytimes.com脚本是超级复杂的。我是16岁,没有太多的程序员,所以这绝对是我的联盟之外。最简单的方法这样做是为了检测文档上的 mouseup
和 keyup
事件,并检查是否选择任何文本。以下内容将适用于所有主流浏览器。
示例:
function getSelectedText(){
var text =;
if(typeof window.getSelection!=undefined){
text = window.getSelection()。toString();
} else if(typeof document.selection!=undefined&& document.selection.type ==Text){
text = document.selection.createRange()。
}
返回文字;
}
函数doSomethingWithSelectedText(){
var selectedText = getSelectedText();
if(selectedText){
alert(Got selected text+ selectedText);
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
I'm writing a Firefox addon that is triggered whenever a word is highlighted. However I need a script that detects when a word is highlighted, and I'm stuck. An example would be nytimes.com (when you're reading an article and you highlight a word, the reference icon pops up). However the nytimes.com script is super complex. I'm 16 and not much of a programmer, so that is definitely way out of my league.
The easiest way to do this is to detect mouseup
and keyup
events on the document and check whether any text is selected. The following will work in all major browsers.
Example: http://www.jsfiddle.net/timdown/SW54T/
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
alert("Got selected text " + selectedText);
}
}
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
这篇关于Javascript:如何检测一个单词是否突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!