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>

转载于:https://www.cnblogs.com/twilight/archive/2010/02/06/1664778.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值