从点获取DOM文本节点? [英] Get DOM text node from point?

查看:124
本文介绍了从点获取DOM文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我可以从 document.elementFromPoint document.getElementFromPoint 中得到一个元素,是吗如果点在文本节点,可能以某种方式获取文本节点?我猜,如果至少我可以得到文本节点的位置和大小,我可以找出它们中的哪一个包含的点。但是DOM节点没有位置属性。是否可以这样做?

Just like I can get an element from a point with document.elementFromPoint or document.getElementFromPoint, is it possible to somehow get a text node if the point is at a text node? I guess if at least I could get the text node's position and size I could then figure out which of them contains the point. But then DOM nodes don't have position properties. Is it possible to do this at all?

推荐答案

这是一个在所有当前浏览器中可用的实现:
< a href =https://github.com/nuxodin/q1/blob/master/q1.dom.js =noreferrer> https://github.com/nuxodin/q1/blob/master/q1。 dom.js

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;
};

这篇关于从点获取DOM文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆