如何获取突出显示文本所在的元素? [英] How can I get the element in which highlighted text is in?

查看:124
本文介绍了如何获取突出显示文本所在的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何编写一个书签,我可以突出显示一些文本,点击书签,让它告诉我突出显示的是什么。我可以做到这一点,但接下来我想知道该文本是什么元素。

I am trying to learn how to write a bookmarklet where I can highlight some text, click on the bookmarklet and have it tell me what got highlighted. I can get that far, but next I want to know what element that text is in.

例如:

<div id="some-id">to be highlighted</div>

书签代码:

javascript:(function(){alert(window.getSelection();})()

如果我突出显示要突出显示文本,然后单击书签,它将提醒文本。但是如何获取文本所在的元素,在这种情况下是后面的元素?

If I highlight the text "to be highlighted" and then click on the bookmarklet, it will alert the text. But how can I get the element in which the text is in, in this case the element after that?

所以流程是:突出显示文本,点击bookmarklet,bookmarklet告诉你突出显示的内容及其所在的元素。

So the flow is: highlight text, click bookmarklet, bookmarklet tells you what you highlighted and the element it's in.

谢谢!

推荐答案

尝试类似的方法来获取包含所选文本的dom元素。

Try something similar to this to get the dom element that contains the selected text.

window.getSelection().anchorNode.parentNode

它适用于firefox和Chorme,你应该将它测试到剩下的浏览器中。

It works on firefox and Chorme, you should test it into the remaining browsers.

如果你选择看到的文字,它有一个怪癖不仅仅是一个元素,只返回第一个元素。但也许你可以与此同住。

It have a quirk, if you select text that beholds to more than an element, only the first one is returned. But maybe you can live with this.

仅供参考什么是anchorNode属性:
http://help.dottoro.com/ljkstboe.php

Just for reference on what is the anchorNode property: http://help.dottoro.com/ljkstboe.php

在Internet Explorer上,这个代码片段应该可以解决问题(我无法测试它)

On internet explorer this snippet should do the trick (I can't test it)

document.selection.createRange().parentElement();


所述 http://msdn.microsoft.com/en-us/library/ms535872.aspx
http://msdn.microsoft.com/en-us/library/ms536654.aspx

关于quirksmode的范围说明: http:/ /www.quirksmode.org/dom/range_intro.html

A range explanation on quirksmode: http://www.quirksmode.org/dom/range_intro.html

这篇关于如何获取突出显示文本所在的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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