现在的位置: 首页 > 综合 > 正文

记录光标在编辑器中的位置

2013年10月27日 ⁄ 综合 ⁄ 共 2429字 ⁄ 字号 评论关闭
 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>无标题文档</title>
  6. </head>
  7. <body>
  8. <script type="text/javascript">
  9. function $(ele){return document.getElementById(ele)}
  10. //记录编辑器中的位置
  11.          var selection_start;
  12.          var selection_end;
  13.          function savePos(textBox){
  14.             var start=0;
  15.             var end=0;          
  16.             if(typeof(textBox.selectionStart) == "number"){   // not ie
  17.                 //alert(typeof(textBox.selectionStart) );
  18.                 start = textBox.selectionStart;
  19.                 end = textBox.selectionEnd;
  20.             }           
  21.             else if(document.selection){
  22.                 var range = document.selection.createRange();
  23.                 if(range.parentElement().id == textBox.id){                 
  24.                     var range_all = document.body.createTextRange();
  25.                     range_all.moveToElementText(textBox);                   
  26.                     for (start=0; range_all.compareEndPoints("StartToStart", range) < 0; start++)
  27.                         range_all.moveStart('character', 1);                    
  28.                     for (var i = 0; i <= start; i ++){
  29.                         if (textBox.value.charAt(i) == '/n')
  30.                             start++;
  31.                     }                   
  32.                      var range_all = document.body.createTextRange();
  33.                      range_all.moveToElementText(textBox);                   
  34.                      for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end ++)
  35.                          range_all.moveStart('character', 1);                        
  36.                          for (var i = 0; i <= end; i ++){
  37.                              if (textBox.value.charAt(i) == '/n')
  38.                                  end ++;
  39.                          }
  40.                     }
  41.                 }
  42.                 selection_start = start;
  43.                 selection_end = end;               
  44.          }
  45. </script>
  46. <form action="" id="test">
  47. <textarea id="t" onfocus="savePos(this);$('log').value=selection_start"  onkeydown="savePos(this);$('log').value=selection_start" onmousedown="savePos(this);$('log').value=selection_start" onmouseup="savePos(this);$('log').value=selection_start" >
  48. </textarea>
  49. <input type="text" id="log" />
  50. </form>
  51. </body>
  52. </html>

抱歉!评论已关闭.