JS - 获取页面上选中的文字

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

 1 function getSelectedText() {
 2   if (window.getSelection) {
 3     // This technique is the most likely to be standardized.
 4     // getSelection() returns a Selection object, which we do not document.
 5     return window.getSelection().toString();
 6   }else if (document.getSelection) {
 7     // This is an older, simpler technique that returns a string
 8     return document.getSelection();
 9   }else if (document.selection) {
10     // This is the IE-specific technique.
11     // We do not document the IE selection property or TextRange objects.
12     return document.selection.createRange().text;
13   }
14 }

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

1 function getTextFieldSelection(e) {
2   if (e.selectionStart != undefined && e.selectionEnd != undefined) {
3     var start = e.selectionStart;
4     var end = e.selectionEnd;
5     return e.value.substring(start, end);
6   }else return ""// Not supported on this browser
7 }


转载自:http://www.codebit.cn/pub/html/javascript/tip/get_selection/
posted on 2009-11-03 22:49  L.Rain  阅读(2056)  评论(0编辑  收藏  举报