问题
How would one go about detecting what has been selected on a page in a browser? Example: Click, hold, select 3 words and 1 image on a page, release.
Sub-question: How to detect what letter someone clicked on?
Without using: A span injector breaking everything up OR a WYSIWYG plugin
I'm hoping this isn't just a type of browser interaction you can't detect.
There could be many uses, but my goal is a simple 'live' page editor, or at least a way to know what someone is clicking on/selecting aside from just the id of an element.
回答1:
window.getSelection() is what you need in all major browsers except IE < 9, which has a different API. window.getSelection()
returns a Selection (spec) object from which you can extract a DOM Range (spec) representing the selection.
For IE < 9, you can look at document.selection, or use a library such as my own Rangy, which provides the same standards-based API in all major browsers.
来源:https://stackoverflow.com/questions/12403345/detect-what-is-selected-highlighted-or-clicked-within-an-element-on-a-page