Javascript:如何检测单词是否突出显示
我正在编写一个 Firefox 插件,只要突出显示一个单词就会触发该插件。但是,我需要一个脚本来检测某个单词何时突出显示,但我陷入了困境。一个例子是 nytimes.com(当您阅读一篇文章并突出显示一个单词时,会弹出参考图标)。然而 nytimes.com 的脚本非常复杂。我今年 16 岁,不太擅长程序员,所以这绝对超出了我的能力范围。
I'm writing a Firefox addon that is triggered whenever a word is highlighted. However I need a script that detects when a word is highlighted, and I'm stuck. An example would be nytimes.com (when you're reading an article and you highlight a word, the reference icon pops up). However the nytimes.com script is super complex. I'm 16 and not much of a programmer, so that is definitely way out of my league.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的方法是检测文档上的
mouseup
和keyup
事件并检查是否选择了任何文本。以下内容适用于所有主要浏览器。示例: http://www.jsfiddle.net/timdown/SW54T/
The easiest way to do this is to detect
mouseup
andkeyup
events on the document and check whether any text is selected. The following will work in all major browsers.Example: http://www.jsfiddle.net/timdown/SW54T/
这是一个脚本:
由 Code Toad 提供:
http://www.codetoad.com/javascript_get_selected_text.asp< /a>
在您的情况下,您可能希望在做出选择时调用此脚本,然后您可以按照您的意愿处理它,例如使用 AJAX 请求来获取相关信息,就像 NYtimes 可能做的那样。
Here is a script:
Courtesy of Code Toad:
http://www.codetoad.com/javascript_get_selected_text.asp
In your case, you would want to call this script when the selection is made, and then you can process it however you wish, with an AJAX request to get relevant information for example, like NYtimes probably does.
就我而言,我希望能够突出显示一行中的文本,然后单击该行并将我发送到其他路线,例如“/entity/:id”;
我创建了一个检测鼠标突出显示某些文本的函数:
然后我将其添加到的行中,
这样用户可以突出显示名称字段或单击其他位置并转到“/entity/:id”
In my case I wanted to be able to either highlight a text in a row of the and click in the row and send me to other route like "/entity/:id";
I created one function that detects the mouse is highlighting some text:
then I added this to the row of the
in this way the user can hightlight then name field or click somewhere else and goes to "/entity/:id"
使用 rangy.js 和 jQuery:
Using rangy.js and jQuery: