Javascript 获取页面上选中的文字

IE可以调用:

  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 中选中的文字,可以用下面的方法:

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

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Language" content="zh-cn" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> 在文本框光标处插入文字 - 枫芸志</title>
</head>
<body>
<div><textarea id="text" cols="50" rows="5">先在本文框中点击鼠标或选择文本以确定光标位置和选取内容。
——晴枫</textarea></div>
<div>
    <input type="button" value="插入文字“China”" onclick="javascript:insert('China');" />
    <input type="button" value="插入文字“C中国N”" onclick="javascript:insert('C中国N');" />
</div>
<br />
<div id="info"></div>
<script type="text/javascript" language="javascript">
<!--
function insert(str){
    var t = document.getElementById("text");
    var i = document.getElementById("info");
    t.focus();
    if (document.all){
        var r = document.selection.createRange();
        document.selection.empty();
        i.innerHTML = "文本框内选取的文字:" + r.text;
        r.text = str;
    }
    else{
        var start = t.selectionStart;
        var end = t.selectionEnd;
        var newStart = start + str.length;
        i.innerHTML = "文本框内选取的文字:" + t.value.substring(start, end);
        t.value = t.value.substring(0,start) + str + t.value.substring(end);
        t.selectionStart = newStart;
        t.selectionEnd = newStart;
    }
}
-->
</script>
</body>
</html>

你可能感兴趣的:(JavaScript,function,input,insert,firefox,button)