[removed] How to detect if a word is highlighted

2019-01-04 01:30发布

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.

3条回答
看我几分像从前
2楼-- · 2019-01-04 01:45

Here is a script:

<script>
function getSelText()
{
    var txt = '';
    if (window.getSelection)
    {
        txt = window.getSelection();
    }
    else if (document.getSelection)
    {
        txt = document.getSelection();
    }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
    }
    else return;
document.aform.selectedtext.value = txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<form name="aform">
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>

Courtesy of Code Toad:

http://www.codetoad.com/javascript_get_selected_text.asp

In your case, you would want to call this script when the selection is made, and then you can process it however you wish, with an AJAX request to get relevant information for example, like NYtimes probably does.

查看更多
Melony?
3楼-- · 2019-01-04 01:48

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;
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-04 01:56

Using rangy.js and jQuery:

$('#elem').on('keyup mouseup', function(){
    var sel = rangy.getSelection()
    if (sel.rangeCount === 0 || sel.isCollapsed) return
    alert(sel.toString())
})
查看更多
登录 后发表回答