Javascript: How to detect if a word is highlighted

余生长醉 提交于 2019-11-26 05:58:25

问题


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.


回答1:


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;



回答2:


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.




回答3:


Using rangy.js and jQuery:

$('#elem').on('keyup mouseup', function(){
    var sel = rangy.getSelection()
    if (sel.rangeCount === 0 || sel.isCollapsed) return
    alert(sel.toString())
})


来源:https://stackoverflow.com/questions/4712310/javascript-how-to-detect-if-a-word-is-highlighted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!