Javascript:如何检测一个单词是否突出显示 [英] Javascript: How to detect if a word is highlighted

查看:98
本文介绍了Javascript:如何检测一个单词是否突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Firefox插件,每当一个单词突出显示时都会触发。然而,我需要一个脚本来检测一个单词突出显示的时间,我被卡住了。一个例子是nytimes.com(当你阅读一篇文章,你突出显示一个字,引用图标弹出)。然而,nytimes.com脚本是超级复杂的。我是16岁,没有太多的程序员,所以这绝对是我的联盟之外。

解决方案

最简单的方法这样做是为了检测文档上的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆