跨浏览器的方法,用于得到光标选中的文字,来自<<javascript: The Definitive Guide>>
function getSelectedText() { if (window.getSelection) { // This technique is the most likely to be standardized. // getSelection() returns a Selection object, which we do not document. return window.getSelection().toString(); } else if (document.getSelection) { // This is an older, simpler technique that returns a string return document.getSelection(); } else if (document.selection) { // This is the IE-specific technique. // We do not document the IE selection property or TextRange objects. return document.selection.createRange().text; } }
There is one minor incompatibility in the Example. The getSelection() methods of the Window and Document object do not return selected text if it is within an <input> or <textarea> form element: they only return text selected from the body of the document itself. The IE document.selection property, on the other hand, returns selected text from anywhere in the document.
In Firefox, text input elements define selectionStart and selectionEnd properties that you can use to query (or set) the selected text. For example:
function getTextFieldSelection(e) { if (e.selectionStart != undefined && e.selectionEnd != undefined) { var start = e.selectionStart; var end = e.selectionEnd; return e.value.substring(start, end); } else return ""; // Not supported on this browser }