如何知道选择范围内是否存在链接元素

发布于 2024-11-08 19:27:17 字数 306 浏览 0 评论 0原文

在 Javascript 中,我想确定一个元素(例如 A 元素)是否存在于给定范围/textRange 内。目的是确定用户当前的选择是否包含链接。我正在构建一个富文本编辑器控件。

range 对象具有 commonAncestorContainer (W3C) 或parentElement() (Microsoft) 方法,该方法返回范围中所有元素的最接近的公共祖先。但是,在该元素内部查找 A 元素是行不通的,因为该共同祖先还可能包含不在范围内的元素,因为范围可以通过父级开始或结束。

你将如何实现这一目标?

In Javascript, I'd like determine whether an element, say an A element, exists inside a given range/textRange. The aim is to determine if the user's current selection contains a link. I am building a rich text editor control.

The range object has a commonAncestorContainer (W3C) or parentElement() (Microsoft) method which returns the closest common anscestor of all elements in the range. However, looking inside this element for A elements won't work, since this common ancestor may also contain elements that aren't in the range, since the range can start or end part way through a parent.

How would you achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

对你的占有欲 2024-11-15 19:27:17

Selection.containsNode 怎么样?
https://developer.mozilla.org/en/DOM/Selection/containsNode

类似:

var selection = window.getSelection();
var range = selection.getRangeAt(0);
var result = $('a', range.commonAncestorContainer).filter(function() {
  return selection.containsNode(this);
});
console.log(result);

How about selection.containsNode?
https://developer.mozilla.org/en/DOM/Selection/containsNode

something like:

var selection = window.getSelection();
var range = selection.getRangeAt(0);
var result = $('a', range.commonAncestorContainer).filter(function() {
  return selection.containsNode(this);
});
console.log(result);
风轻花落早 2024-11-15 19:27:17

我最终采用了这样的解决方案:

        var findinselection = function(tagname, container) {
            var
                i, len, el,
                rng = getrange(),
                comprng,
                selparent;
            if (rng) {
                selparent = rng.commonAncestorContainer || rng.parentElement();
                // Look for an element *around* the selected range
                for (el = selparent; el !== container; el = el.parentNode) {
                    if (el.tagName && el.tagName.toLowerCase() === tagname) {
                        return el;
                    }
                }
                // Look for an element *within* the selected range
                if (!rng.collapsed && (rng.text === undefined || rng.text) &&
                    selparent.getElementsByTagName) {
                    el = selparent.getElementsByTagName(tagname);
                    comprng = document.createRange ?
                        document.createRange() : document.body.createTextRange();
                    for (i = 0, len = el.length; i < len; i++) {

                        // determine if element el[i] is within the range
                        if (document.createRange) { // w3c
                            comprng.selectNodeContents(el[i]);
                            if (rng.compareBoundaryPoints(Range.END_TO_START, comprng) < 0 &&
                                rng.compareBoundaryPoints(Range.START_TO_END, comprng) > 0) {
                                return el[i];
                            }
                        }
                        else { // microsoft
                            comprng.moveToElementText(el[i]);
                            if (rng.compareEndPoints("StartToEnd", comprng) < 0 &&
                                rng.compareEndPoints("EndToStart", comprng) > 0) {
                                return el[i];
                            }
                        }
                    }
                }
            }
        };

其中 getrange() 是我的另一个函数,用于将当前选择作为范围对象获取。

要使用它,请像

var link = findselection('a', editor);

其中编辑器是可内容编辑元素或设计模式 iframe 中的主体一样调用它。

I ended up going with a solution like this:

        var findinselection = function(tagname, container) {
            var
                i, len, el,
                rng = getrange(),
                comprng,
                selparent;
            if (rng) {
                selparent = rng.commonAncestorContainer || rng.parentElement();
                // Look for an element *around* the selected range
                for (el = selparent; el !== container; el = el.parentNode) {
                    if (el.tagName && el.tagName.toLowerCase() === tagname) {
                        return el;
                    }
                }
                // Look for an element *within* the selected range
                if (!rng.collapsed && (rng.text === undefined || rng.text) &&
                    selparent.getElementsByTagName) {
                    el = selparent.getElementsByTagName(tagname);
                    comprng = document.createRange ?
                        document.createRange() : document.body.createTextRange();
                    for (i = 0, len = el.length; i < len; i++) {

                        // determine if element el[i] is within the range
                        if (document.createRange) { // w3c
                            comprng.selectNodeContents(el[i]);
                            if (rng.compareBoundaryPoints(Range.END_TO_START, comprng) < 0 &&
                                rng.compareBoundaryPoints(Range.START_TO_END, comprng) > 0) {
                                return el[i];
                            }
                        }
                        else { // microsoft
                            comprng.moveToElementText(el[i]);
                            if (rng.compareEndPoints("StartToEnd", comprng) < 0 &&
                                rng.compareEndPoints("EndToStart", comprng) > 0) {
                                return el[i];
                            }
                        }
                    }
                }
            }
        };

Where getrange() is another function of mine to get the current selection as a range object.

To use, call it like

var link = findselection('a', editor);

Where editor is the contenteditable element, or body in a designmode iframe.

执笏见 2024-11-15 19:27:17

跨浏览器做这件事有点痛苦。您可以使用我的 Rangy 库,这对于这项任务来说可能有点过分了,但确实让它变得更简单并适用于所有主要浏览器。以下代码假设仅选择一个范围:

var sel = rangy.getSelection();
if (sel.rangeCount) {
    var range = sel.getRangeAt(0);
    var links = range.getNodes([1], function(node) {
        return node.tagName.toLowerCase() == "a" && range.containsNode(node);
    });
}

This is a bit of a pain in the bum to do cross-browser. You could use my Rangy library, which is probably overkill for just this task but does make it more straightforward and works in all major browsers. The following code assumes only one Range is selected:

var sel = rangy.getSelection();
if (sel.rangeCount) {
    var range = sel.getRangeAt(0);
    var links = range.getNodes([1], function(node) {
        return node.tagName.toLowerCase() == "a" && range.containsNode(node);
    });
}
漫雪独思 2024-11-15 19:27:17

我正在使用适用于 IE / Chrome / FF 的代码:(我使用它来选择表中的行 )

// yourLink is the DOM element you want to check
var selection = window.getSelection().getRangeAt(0)
var node = document.createRange()
node.selectNode(yourLink)
var s2s = selection.compareBoundaryPoints(Range.START_TO_END, node)
var s2e = selection.compareBoundaryPoints(Range.START_TO_START, node)
var e2s = selection.compareBoundaryPoints(Range.END_TO_START, node)
var e2e = selection.compareBoundaryPoints(Range.END_TO_END, node)
if ((s2s != s2e) || (e2s != e2e) || (s2s!=e2e))
    console.log("your node is inside selection")

I'm using this code that works with IE / Chrome / FF: (I'm using it to select rows <tr> in a table)

// yourLink is the DOM element you want to check
var selection = window.getSelection().getRangeAt(0)
var node = document.createRange()
node.selectNode(yourLink)
var s2s = selection.compareBoundaryPoints(Range.START_TO_END, node)
var s2e = selection.compareBoundaryPoints(Range.START_TO_START, node)
var e2s = selection.compareBoundaryPoints(Range.END_TO_START, node)
var e2e = selection.compareBoundaryPoints(Range.END_TO_END, node)
if ((s2s != s2e) || (e2s != e2e) || (s2s!=e2e))
    console.log("your node is inside selection")
北方。的韩爷 2024-11-15 19:27:17

对于搜索元素上的范围,我写的内容很有用。 (但仅适用于这种情况!)

首先,我编写了一个返回在范围内找到的节点的函数:getNodeFromRange(rangeObject)。使用此函数,可以轻松编写返回所需节点的函数:findTagInRange(tagName)。

function getNodeFromRange(range) {
    if(range.endContainer.nodeType==Node.ELEMENT_NODE) {
        return range.endContainer;
    }
    if(range.endContainer.nodeType==Node.TEXT_NODE) {
        return range.endContainer.parentNode;
    }
    else {
        // the 'startContainer' it isn't on an Element (<p>, <div>, etc...)
        return;
    }
}

function findTagInRange(tagName, range) {
    var node = getNodeFromRange(range);
    if(node && typeof(node.tagName)!='undefiend' && node.tagName.toLowerCase()==tagName.toLowerCase()) {
        return $(node);
    }
    return;
}

然后我可以按如下方式使用它:

var link = findTagInRange('A', range);

我看到了您已经解决的范围的确定。 :)

In the case of the range on the searched element, what I wrote is useful. (But only for that case!)

First I wrote a function that returns the Node found in the range: getNodeFromRange(rangeObject). Using this function it was already easy to write the function that returns the desired Node: findTagInRange(tagName).

function getNodeFromRange(range) {
    if(range.endContainer.nodeType==Node.ELEMENT_NODE) {
        return range.endContainer;
    }
    if(range.endContainer.nodeType==Node.TEXT_NODE) {
        return range.endContainer.parentNode;
    }
    else {
        // the 'startContainer' it isn't on an Element (<p>, <div>, etc...)
        return;
    }
}

function findTagInRange(tagName, range) {
    var node = getNodeFromRange(range);
    if(node && typeof(node.tagName)!='undefiend' && node.tagName.toLowerCase()==tagName.toLowerCase()) {
        return $(node);
    }
    return;
}

And then I can use it as follows:

var link = findTagInRange('A', range);

And I see the determination of the range you've already solved. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文