处理火狐getSelection无法读取文本框及输入框里内容的问题

  |   2 |   Code |

attention:不仅仅是文本框内的选择会被脚本记录,在本页面内所有的选取都会被记录



Drag to select text (script runs on mouseup)






源码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script type="text/javascript">
function GetSelectedText (){
  var userSelection, ta;
  if (window.getSelection && document.activeElement){
    if (document.activeElement.nodeName == "TEXTAREA" ||
        (document.activeElement.nodeName == "INPUT" &&
        document.activeElement.getAttribute("type").toLowerCase() == "text")){
      ta = document.activeElement;
      userSelection = ta.value.substring(ta.selectionStart, ta.selectionEnd);
    } else {
      userSelection = window.getSelection();
    }
    document.getElementById("seltext").innerHTML += "Selection="+userSelection.toString()+" [1]<br>";
  } else {
    // all browsers, except IE before version 9
    if (document.getSelection){       
        userSelection = document.getSelection();
        document.getElementById("seltext").innerHTML += "Selection="+userSelection.toString()+" [2]<br>";
    }
    // IE below version 9
    else if (document.selection){
        userSelection = document.selection.createRange();
        document.getElementById("seltext").innerHTML += "Selection="+userSelection.text+" [3]<br>";
    }
  }
}
</script>
</head>
<body onmouseup="GetSelectedText()">
<h1>Drag to select text (script runs on mouseup)</h1>
<textarea rows="5" cols="30">Select text or part of it.</textarea><br>
<input type="text" name="text1" value="Some more play text" size="50"><br>
<div id="seltext"></div>

来源

http://forums.mozillazine.org/viewtopic.php?f=25&t=2268557

Comments
Write a Comment