我可以通过选择文本或文本区域之外的文本来获取 Javascript 事件吗?
我想知道用户何时使用 Javascript 在 html 页面中选择文本。文本不应是可编辑的。 onselect
事件似乎仅适用于
有没有办法用这些标签解决这个问题?
有完全不同的方法吗?
I would like to know when a user selects text in an html page using Javascript. The text should not be editable. The onselect
event seems to be only applicable to <textarea>
and <input type="TEXT">
tags. The event is not fired if either tag is disabled.
Is there a way around this with these tags?
Is there a completely different approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,这里有一个例子: http://www.codetoad.com/javascript_get_selected_text.asp
使用您在此处看到的内容,您可以将事件绑定到文档正文的单击/释放事件,并检查是否有选择,以及选择的时间长短,以确定他们是否选择了任何文本。
StackOverflow 存档:
Sure, an example exists here: http://www.codetoad.com/javascript_get_selected_text.asp
Using what you see here, you could bind events to the click/release events of the document body, and check to see if there is a selection, and how long the selection is to determine if they've selected any text.
StackOverflow Archive:
您可以捕获
mouseUp
事件,并使用window.getSelection()
检查是否选择了某些文本。然而,此方法可能不跨浏览器兼容(
window.getSelection()
)。编辑:这是一个带有
mouseUp
绑定的非常完整的示例:http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.htmlYou could capture the
mouseUp
event, and check if some text is selected usingwindow.getSelection()
.This method may however not be cross-browser compatible (the
window.getSelection()
).EDIT: here is a pretty complete example with
mouseUp
binding : http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html以跨浏览器的方式做到这一点并不容易。在 IE 中,只有
select
事件适用于正文和表单输入,因此可以执行您想要的操作,但要检测用户何时以跨浏览器方式进行选择,您需要处理keyup
和mouseup
事件。即使如此,您也不会检测到选择事件,例如用户使用“全选”菜单选项(通常在“编辑”和右键单击上下文菜单中找到)。因此,您需要定期轮询并检查选择对象的属性(通过 IE 中的window.getSelection()
或document.selection
获得)。This is not easy to do in a cross-browser way. In IE only the
select
event applies to body text as well as form inputs so would do what you want, but to detect when the user has made a selection in a cross-browser way you will need to handle bothkeyup
andmouseup
events. Even then you won't be detecting selection events such as the user using the "Select all" menu option (usually found in the Edit and right click context menus). So you're down to polling at regular intervals and checking properties of the selection object (obtained viawindow.getSelection()
ordocument.selection
in IE).