Get DOM text node from point?

前端 未结 4 1950
无人共我
无人共我 2020-12-30 06:49

Just like I can get an element from a point with document.elementFromPoint or document.getElementFromPoint, is it possible to somehow get a text no

相关标签:
4条回答
  • 2020-12-30 07:29

    For Firefox, you should use document.caretPositionFromPoint

    Here's a greap demo: https://developer.mozilla.org/en-US/docs/Web/API/document.caretPositionFromPoint

    For Chrome and Edge, try document.caretRangeFromPoint(x,y)

    0 讨论(0)
  • 2020-12-30 07:33

    Considering this document (fiddle):

    <html>
    <body>
        some text here 
        <p id="para1">lalala</p> 
        bla bla
    </body>
    </html>​
    

    And this code:

    $(document).on('click', function(evt) {
        var elem = document.elementFromPoint(evt.clientX, evt.clientY);
        console.log(elem);
    });
    

    When you click anywhere inside the <p> tag, the tag element itself is logged. However, when the surrounding text is clicked, the <body> is returned because text fragments are not considered elements.

    Conclusion

    It's not possible to accomplish what you want with elementFromPoint() and because text fragments don't receive click events, I don't think it's possible at all.

    0 讨论(0)
  • 2020-12-30 07:42

    You can use element.nodeName to see if it's a text node, and then element.nodeValue for its value.

    0 讨论(0)
  • 2020-12-30 07:47

    Here is an implementation that works in all current browsers: https://github.com/nuxodin/q1/blob/master/q1.dom.js

    document.betaNodeFromPoint = function(x, y){
        var el = document.elementFromPoint(x, y);
        var nodes = el.childNodes;
        for ( var i = 0, n; n = nodes[i++];) {
            if (n.nodeType === 3) {
                var r = document.createRange();
                r.selectNode(n);
                var rects = r.getClientRects();
                for ( var j = 0, rect; rect = rects[j++];) {
                    if (x > rect.left && x < rect.right && y > rect.top && y < rect.bottom) {
                        return n;
                    }
                }
            }
        }
        return el;
    };
    
    0 讨论(0)
提交回复
热议问题