从 FF/Webkit 中的像素位置创建折叠范围

2022-01-24 00:00:00 position range javascript

使用 JavaScript,我想从一个像素位置创建一个折叠范围,以便在该位置标识的范围之后在文档流中插入新节点.

Using JavaScript, I would like to create a collapsed range from a pixel position, in order to insert new nodes in the flow of the document, after the range identified by this position.

这可以通过 Internet Explorer 中的 TextRange 对象来完成(moveToPoint(x, y) 方法).

This can be done with the TextRange object in Internet Exporer (moveToPoint(x, y) method).

如何在 FireFox 中做到这一点?网络套件?

我可以从 document.elementFromPoint(x, y) 的位置获取容器元素.但是当位置恰好在文本节点内时,如何获取有关构建范围所需的文本偏移量的更多信息?

I can get the container element from the position with document.elementFromPoint(x, y). But when the position happens to be inside a text node, how do I get more information about the text offset required to build a range?

推荐答案

这是我为旧浏览器实现的 caretRangeFromPoint:

Here is my implementation of caretRangeFromPoint for old browsers:

if (!document.caretRangeFromPoint) {
    document.caretRangeFromPoint = function(x, y) {
        var log = "";

        function inRect(x, y, rect) {
            return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
        }

        function inObject(x, y, object) {
            var rects = object.getClientRects();
            for (var i = rects.length; i--;)
                if (inRect(x, y, rects[i]))
                    return true;
            return false;
        }

        function getTextNodes(node, x, y) {
            if (!inObject(x, y, node))
                return [];

            var result = [];
            node = node.firstChild;
            while (node) {
                if (node.nodeType == 3)
                    result.push(node);
                if (node.nodeType == 1)
                    result = result.concat(getTextNodes(node, x, y));

                node = node.nextSibling;
            }

            return result;
        }

        var element = document.elementFromPoint(x, y);
        var nodes = getTextNodes(element, x, y);
        if (!nodes.length)
            return null;
        var node = nodes[0];

        var range = document.createRange();
        range.setStart(node, 0);
        range.setEnd(node, 1);

        for (var i = nodes.length; i--;) {
            var node = nodes[i],
                text = node.nodeValue;


            range = document.createRange();
            range.setStart(node, 0);
            range.setEnd(node, text.length);

            if (!inObject(x, y, range))
                continue;

            for (var j = text.length; j--;) {
                if (text.charCodeAt(j) <= 32)
                    continue;

                range = document.createRange();
                range.setStart(node, j);
                range.setEnd(node, j + 1);

                if (inObject(x, y, range)) {
                    range.setEnd(node, j);
                    return range;
                }
            }
        }

        return range;
    };
}

相关文章