getSelection();

在一些特殊应用中,我们需要获取页面上选中的文字,但是要实现这一需求,我们不得不面对那恼人的兼容问题,本文介绍了一个兼容性较好的解决方法。同时,也提供了一个在 FireFox 下获取 input 和 textarea 中选中文字的解决方案。

获取选中的普通页面上的文字,可以用下面的方法:
1. 
2. <script type="text/javascript">
3. 
4. // 说明:获取页面上选中的文字
5. // 整理:http://www.codebit.cn/
6. 
7. function getSelectedText() {
8.     if (window.getSelection) {
9.         // This technique is the most likely to be standardized.
10.         // getSelection() returns a Selection object, which we do not document.
11.         return window.getSelection().toString();
12.     }
13.     else if (document.getSelection) {
14.         // This is an older, simpler technique that returns a string
15.         return document.getSelection();
16.     }
17.     else if (document.selection) {
18.         // This is the IE-specific technique.
19.         // We do not document the IE selection property or TextRange objects.
20.         return document.selection.createRange().text;
21.     }
22. }
23. 
24. </script>


在 FireFox 下获取 input 或者 textarea 中选中的文字,可以用下面的方法:


2. <script type="text/javascript">
3. 
4. // 说明:FireFox 下获取 input 或者 textarea 中选中的文字
5. // 整理:http://www.codebit.cn/
6. 
7. function getTextFieldSelection(e) {
8.     if (e.selectionStart != undefined && e.selectionEnd != undefined) {
9.         var start = e.selectionStart;
10.         var end = e.selectionEnd;
11.         return e.value.substring(start, end);
12.     }
13.     else return "";  // Not supported on this browser
14. }
15. 
16. </script>

posted @ 2010-02-06 01:51  waynecn  阅读(2505)  评论(0编辑  收藏  举报