在Javascript中选择的文本事件触发器 [英] Selected text event trigger in Javascript

查看:544
本文介绍了在Javascript中选择的文本事件触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能听起来像一个新手问题,但我想知道当有人使用鼠标在页面上选择给定的文本片段时,我如何触发自定义JavaScript函数。还有什么办法可以在网页上找到所选文字的位置吗?

It may sound a newbie question but I wanted to know how I can trigger a custom JavaScript function when someone selects a given text fragment on a page using mouse. Also is there any way to find the position of selected text on the webpage?

更新:
为了更清楚,文本片段可以是一个句子的一部分或者一个单词或短语或整个段落。

Update: To be more clear, text fragment can be part of a sentence or a word or a phrase or whole a paragraph.

推荐答案

没有选择了文本 (DOM)事件,但您可以将 mouseup 事件绑定到 document.body 。在该事件处理程序中,您可能只需检查

There is no "Text was selected" (DOM) event, but you can bind a mouseup event to the document.body. Within that event handler, you might just check the

document.selection.createRange().text

window.getSelection()

方法。 Stackoverflow上有几个主题,比如 javascript to获取网页中所选文字的段落

methods. There are several topics on Stackoverflow, like this one javascript to get paragraph of selected text in web page.

我不确定你对找到位置的意思,但留在我的榜样世界您可以使用事件属性获取X + Y鼠标位置。

I'm not sure what you mean with "finding the position", but to stay in my example world you could use the event propertys for X+Y mouse positions.

示例: http://www.jsfiddle.net/2C6fB/1/

这篇关于在Javascript中选择的文本事件触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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