Javascript:如何检测一个单词是否突出显示 [英] Javascript: How to detect if a word is highlighted
问题描述
最简单的方法这样做是为了检测文档上的 mouseup
和 keyup
事件,并检查是否选择任何文本。以下内容将适用于所有主流浏览器。
示例: 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()。
}
返回文字;
}
函数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:如何检测一个单词是否突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!