JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

15.10.3 Querying Selected Text

this.buffer = ""; };


15.10.3 Querying Selected Text

It is sometimes useful to be able to determine what text the user has selected within a document. You can do that with a function like this:

function getSelectedText() { if (window.getSelection) // The HTML5 standard API return window.getSelection().toString(); else if (document.selection) // This is the IE-specific technique. return document.selection.createRange().text; }

15.10 Other Document Features | 407

The standard window.getSelection() method returns a Selection object that describes the current selection as a sequence of one or more Range objects. Selection and Range define a fairly complex API that is not commonly used and is not documented in this book. The most important and widely implemented (except in IE) feature of the Selection object is that it has a toString() method that returns the plain text content of the selection.

IE defines a different API that is also left undocumented in this book. document.selection returns an object that represents the selection. The createRange() method of that object returns an IE-specific TextRange object, and the text property of that object contains the selected text.

Code like the above can be particularly useful in bookmarklets ( §13.2.5.1 ) that operate on the selected text by looking up a word with a search engine or reference site. The following HTML link, for example, looks up the currently selected text in Wikipedia. When bookmarked, this link and the JavaScript URL it contains become a bookmarklet:

Look Up Selected Text In Wikipedia


There is an incompatibility in the selection querying code shown above: the getSelection()method of the Window object does not return selected text if it is within anorform element: it only returns 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.

To obtain the selected text from a text input field orelement, use this code: elt.value.substring(elt.selectionStart, elt.selectionEnd);

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31439.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1