简体   繁体   English

jQuery事件以检测文本的取消选择

[英]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? jQuery是否捕获了这样的事件,可以在取消选择文本检测到对文本的取消选择? 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). 到目前为止,我一直在使用一种方法来捕获对文档正文的单击,但是click(或mouseup)会在清除文本之前获得对文本的选择(通过单击文档中的其他位置一次)。

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. 上面的方法成功工作是因为,显然,在选择了文本之后会触发正文上的click事件。 But I would like a cleaner way. 但是我想要一种更清洁的方式。

Note: this operation is done on a DIV, not on an an INPUT or TEXTAREA element. 注意:此操作在DIV上完成,而不是在INPUT或TEXTAREA元素上完成。

You can use Selection - object represents the range of text selected by the user or the current position. 您可以使用Selection-对象代表用户选择的文本范围或当前位置。 Your question already answered into Stacks: 您的问题已回答堆栈:

get selected text's html in div 在div中获取选定文本的html

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 编辑:如果它们在范围内,则可以将AnchorOffset和FocusOffset存储到会话中,然后进行比较,简单

$(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 :) 编辑:下次,我会读得更好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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