亲宝软件园·资讯

展开

JavaScript记录光标在编辑器中位置的实现方法

zhangw428 人气:0

本文实例讲述了JavaScript记录光标在编辑器中位置的实现方法。分享给大家供大家参考,具体如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script type="text/javascript">
function $(ele){return document.getElementById(ele)}
//记录编辑器中的位置
   var selection_start;
   var selection_end;
   function savePos(textBox){
   var start=0;
   var end=0;
   if(typeof(textBox.selectionStart) == "number"){ // not ie
    //alert(typeof(textBox.selectionStart) );
    start = textBox.selectionStart;
    end = textBox.selectionEnd;
   }
   else if(document.selection){
    var range = document.selection.createRange();
    if(range.parentElement().id == textBox.id){
     var range_all = document.body.createTextRange();
     range_all.moveToElementText(textBox);
     for (start=0; range_all.compareEndPoints("StartToStart", range) < 0; start++)
      range_all.moveStart('character', 1);
     for (var i = 0; i <= start; i ++){
      if (textBox.value.charAt(i) == '/n')
       start++;
     }
      var range_all = document.body.createTextRange();
      range_all.moveToElementText(textBox);
      for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end ++)
       range_all.moveStart('character', 1);
       for (var i = 0; i <= end; i ++){
        if (textBox.value.charAt(i) == '/n')
         end ++;
       }
     }
    }
    selection_start = start;
    selection_end = end;
   }
</script>
<form action="" id="test">
<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" >
</textarea>
<input type="text" id="log" />
</form>
</body>
</html>

希望本文所述对大家JavaScript程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论