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

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

问题描述

我正在编写一个 Firefox 插件,每当突出显示一个词时就会触发该插件.但是,我需要一个脚本来检测单词何时突出显示,但我被卡住了.一个例子是 nytimes.com(当你阅读一篇文章并突出显示一个词时,参考图标会弹出).然而 nytimes.com 脚本非常复杂.我今年 16 岁,还算不上程序员,所以这绝对是我不擅长的.

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.

推荐答案

最简单的方法是检测文档上的mouseupkeyup 事件并检查是否选择任何文本.以下内容适用于所有主要浏览器.

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.

示例: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天全站免登陆