简体   繁体   中英

jQuery event to detect deselection of text

Is there such an event captured by jQuery that I can use to detect the deselection of text after the text has been deselected? So far I've been using a way in which I capture the click on the document's BODY, but the click(or mouseup) get the selection of text before the text is cleared (by clicking somewhere else in the document, once).

Also, is there an event that fires after the user selected some text in the page? The method above works successfully because, apparently, the click event on the body is fired after the text has been selected. But I would like a cleaner way.

Note: this operation is done on a DIV, not on an an INPUT or TEXTAREA element.

You can use Selection - object represents the range of text selected by the user or the current position. Your question already answered into Stacks:

get selected text's html in div

There's, the solution is create a prototype to improve browser's compatibility and stuff. This works too, but I recommend the solution of the link above:

EDIT: You can store the AnchorOffset and the FocusOffset into a session if they are in a range and compare after that, simple

$(function() {
    $(document).on("mouseup", function() {
        var mytext = window.getSelection();
        if (typeof sessionStorage.getItem('initialRange') != 'undefined' && (mytext.anchorOffset != sessionStorage.getItem('initialRange') || mytext.focusOffset != sessionStorage.getItem('finalRange'))){
            //DO WHAT YOU WANT, THE TEXT HAS BEEN DESELECTED
        }
        //take the coordenates of mouseup, when the mouse create a range, store the values
        if (mytext.anchorOffset != mytext.focusOffset){
            sessionStorage.setItem('initialRange', mytext.anchorOffset);
            sessionStorage.setItem('finalRange', mytext.focusOffset);
        }
    });
});

EDIT: Next time, I'll read better :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM