Can I get a Javascript event from the selection of text outside of text or textarea?

∥☆過路亽.° 提交于 2019-12-30 12:14:11

问题


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?


回答1:


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:

  1. What's the event fired when a user selects text on a page?
  2. Javascript to get Paragraph of Selected Text in WebPage



回答2:


You could capture the mouseUp event, and check if some text is selected using window.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




回答3:


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 both keyup and mouseup 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 via window.getSelection() or document.selection in IE).



来源:https://stackoverflow.com/questions/1791526/can-i-get-a-javascript-event-from-the-selection-of-text-outside-of-text-or-texta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!