jquery: select text event

前端 未结 2 887
[愿得一人]
[愿得一人] 2021-01-02 04:57

is it possible that when user selected some text(non textarea nor input), jquery can call my callback to let me know which div\'s text is selected, and if the select focus i

相关标签:
2条回答
  • 2021-01-02 05:27

    you can use this

    use <ELEMENT ondrag = "handler(event);" >

    object.addEventListener( "drag", handler, bCapture);
    
    0 讨论(0)
  • 2021-01-02 05:41

    Somewhat surprisingly, there's no simple way to do this. IE has a select event that is implemented on all elements but other browsers have never extended this beyond inputs. You'll have to handle keyup and mouseup events on the whole document, and even then, your callback may well be called when the selection hasn't actually changed.


    UPDATE 13 OCTOBER 2013

    WebKit browsers have supported the selectionchange event on Document nodes for a couple of years. IE also supports this event back to version 5.5. Example:

    document.onselectionchange = function() {
        console.log("Selection changed");
    };
    

    Here's a simple example:

    function selectCallback(selectionParentElement) {
        console.log("Selecting, parent element is " + selectionParentElement.nodeName);
    }
    
    var mouseOrKeyUpHandler;
    
    if (typeof window.getSelection != "undefined") {
        // Non-IE
        mouseOrKeyUpHandler = function() {
            var sel = window.getSelection();
            if (sel.rangeCount > 0) {
                var range = sel.getRangeAt(0);
                if (range.toString()) {
                    var selParentEl = range.commonAncestorContainer;
                    if (selParentEl.nodeType == 3) {
                        selParentEl = selParentEl.parentNode;
                    }
                    selectCallback(selParentEl);
                }
            }
        };
    } else if (typeof document.selection != "undefined") {
        // IE
        mouseOrKeyUpHandler = function() {
            var sel = document.selection;
            if (sel.type == "Text") {
                var textRange = sel.createRange();
                if (textRange.text != "") {
                    selectCallback(textRange.parentElement());
                }
            }
        };
    }
    
    document.onmouseup = mouseOrKeyUpHandler;
    document.onkeyup = mouseOrKeyUpHandler;
    
    0 讨论(0)
提交回复
热议问题