• 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>

  • 相关阅读:
    常见排序算法导读(8)[堆排序]
    常见排序算法导读(7)[希尔排序]
    常见排序算法导读(6)[快排序]
    常见排序算法导读(5)[冒泡排序]
    常见排序算法导读(4)[直接插入排序]
    UI基础
    iOS8之后CoreLocation定位的使用
    关于什么时候用pop什么时候用dismiss
    控制台输出文字改中文
    Quartz2D使用
  • 原文地址:https://www.cnblogs.com/twilight/p/1664778.html
Copyright © 2020-2023  润新知