如何知道选择范围内是否存在链接元素
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Selection.containsNode 怎么样?
https://developer.mozilla.org/en/DOM/Selection/containsNode
类似:
How about selection.containsNode?
https://developer.mozilla.org/en/DOM/Selection/containsNode
something like:
我最终采用了这样的解决方案:
其中 getrange() 是我的另一个函数,用于将当前选择作为范围对象获取。
要使用它,请像
其中编辑器是可内容编辑元素或设计模式 iframe 中的主体一样调用它。
I ended up going with a solution like this:
Where getrange() is another function of mine to get the current selection as a range object.
To use, call it like
Where editor is the contenteditable element, or body in a designmode iframe.
跨浏览器做这件事有点痛苦。您可以使用我的 Rangy 库,这对于这项任务来说可能有点过分了,但确实让它变得更简单并适用于所有主要浏览器。以下代码假设仅选择一个范围:
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:
我正在使用适用于 IE / Chrome / FF 的代码:(我使用它来选择表中的行 )
I'm using this code that works with IE / Chrome / FF: (I'm using it to select rows <tr> in a table)
对于搜索元素上的范围,我写的内容很有用。 (但仅适用于这种情况!)
首先,我编写了一个返回在范围内找到的节点的函数:getNodeFromRange(rangeObject)。使用此函数,可以轻松编写返回所需节点的函数:findTagInRange(tagName)。
然后我可以按如下方式使用它:
我看到了您已经解决的范围的确定。 :)
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).
And then I can use it as follows:
And I see the determination of the range you've already solved. :)