js实现在光标的位置 添加内容

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
 
<body>
 
 
 
<script   type="text/javascript">   
function setCaret(textObj) {
    if (textObj.createTextRange) {
        textObj.caretPos = document.selection.createRange().duplicate();
    }
}
function insertAtCaret(textObj, textFeildValue) {
    if (document.all) {
        if (textObj.createTextRange && textObj.caretPos) {
            var caretPos = textObj.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '   ' ? textFeildValue + '   ' : textFeildValue;
        } else {
            textObj.value = textFeildValue;
        }
    } else {
        if (textObj.setSelectionRange) {
            var rangeStart = textObj.selectionStart;
            var rangeEnd = textObj.selectionEnd;
            var tempStr1 = textObj.value.substring(0, rangeStart);
            var tempStr2 = textObj.value.substring(rangeEnd);
            textObj.value = tempStr1 + textFeildValue + tempStr2;
        } else {
            alert("This   version   of   Mozilla   based   browser   does   not   support   setSelectionRange");
        }
    }
}   
 </script>  
    
  <form   id="form1"   action=""   onsubmit=""   method="post"   enctype="text/plain">    
  <p>  
  <textarea   name="tarea"   rows=""   cols=""   style="width:300px;height:120px;" 
  onselect="setCaret(this);" 
  onclick="setCaret(this);" 
  onkeyup="setCaret(this);"   >例子例子例子例子例子</textarea>  
  <br/><br/>  
  <input   type="text"   name="textfield"   style="width:220px;"   value="插入FireFox"/>  
  <br/>  
  <input   type="button"   value="插入" 
  onclick="insertAtCaret(this.form.tarea,this.form.textfield.value);"/>  
  </p>  
  </form>   
 
 
<div id="box" contenteditable="true" style="border:1px solid #ccc; width:300px; height:200px;">sljfldjfldf</div>
 
</body>
</html>

  

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
 
<textarea name="" id="txt1" cols="30" rows="10"    >了在IE、Firefox、Opera等主流浏览器的获取光标位置(getCursortPosition)以及设置光标位置(setCursorPosition)的函数。</textarea><br>

<input type="text" name="" id="txt2">
<input type="button" value="添加" id="btn">

<script type="text/javascript">
window.onload = function(){
    var oTxt1 = document.getElementById("txt1");
    var oTxt2 = document.getElementById("txt2");
    var oBtn = document.getElementById("btn");
    oBtn.onclick = function(){
    getValue("txt1", oTxt2.value);
    }
}
</script>
<script type="text/javascript">
//objid:textarea的id   str:要插入的内容
function getValue(objid,str){
   var myField=document.getElementById(""+objid);
   //IE浏览器
     if (document.selection) {
       myField.focus();
       sel = document.selection.createRange();
       sel.text = str;
       sel.select();
     }
   
     //火狐/网景 浏览器
     else if (myField.selectionStart || myField.selectionStart == '0')
     {
     //得到光标前的位置
       var startPos = myField.selectionStart;
       //得到光标后的位置
       var endPos = myField.selectionEnd;
       // 在加入数据之前获得滚动条的高度
       var restoreTop = myField.scrollTop;
       myField.value = myField.value.substring(0, startPos) + str + myField.value.substring(endPos, myField.value.length);
       //如果滚动条高度大于0
       if (restoreTop > 0) {
         // 返回
         myField.scrollTop = restoreTop;
       }
       myField.focus();
       myField.selectionStart = startPos + str.length;
       myField.selectionEnd = startPos + str.length;
     }
     else {
       myField.value += str;
       myField.focus();
     }
   }
</script>


</body>
</html>

  

<!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-Type" content="text/html; charset=UTF-8">  
<title>光标控制器</title>  
<script type="text/javascript">
function cursorControl(a){
    this.element=a;
    this.range=!1;
    this.start=0;
    this.init();
};
cursorControl.prototype={
    init:function(){
        var _that=this;
        this.element.onkeyup=this.element.onmouseup=function(){
            this.focus();
            if(document.all){
                _that.range=document.selection.createRange();
            }else{
                _that.start=_that.getStart();
            }
        }
    },
    getType:function(){
        return Object.prototype.toString.call(this.element).match(/^\[object\s(.*)\]$/)[1];
    },
    getStart:function(){
        if (this.element.selectionStart || this.element.selectionStart == '0'){  
            return this.element.selectionStart; 
        }else if (window.getSelection){  
            var rng = window.getSelection().getRangeAt(0).cloneRange();  
            rng.setStart(this.element,0);  
            return rng.toString().length;
        }
    },
    insertText:function(text){
        this.element.focus();  
        if(document.all){
            document.selection.empty();  
            this.range.text = text;  
            this.range.collapse();  
            this.range.select();
        }  
        else{
            if(this.getType()=='HTMLDivElement'){
                this.element.innerHTML=this.element.innerHTML.substr(0,this.start)+text+this.element.innerHTML.substr(this.start);
            }else{
                this.element.value=this.element.value.substr(0,this.start)+text+this.element.value.substr(this.start);
            };
        } 
    },
    getText:function(){
        if (document.all){  
            var r = document.selection.createRange();  
            document.selection.empty();  
            return r.text;  
        }  
        else{  
            if (this.element.selectionStart || this.element.selectionStart == '0'){
                var text=this.getType()=='HTMLDivElement'?this.element.innerHTML:this.element.value;
                return text.substring(this.element.selectionStart,this.element.selectionEnd); 
            } 
            else if (window.getSelection){  
                return window.getSelection().toString()
            };  
        }  
    }
};
var c1,c2;
window.onload=function(){
    c1=new cursorControl(document.getElementById('text'));
    c2=new cursorControl(document.getElementById('editdiv'));
};
function fn1(str){
    c1.insertText(str);
};
function fn2(str){
    c2.insertText(str);
};
function fn3(){
    alert(c1.getText());
};
function fn4(){
    alert(c2.getText());
}     
</script>  
</head>  
<body>  
    <input type = "button" value = "插入字符串 {文本1}" onclick="fn1('{文本1}');"/><input type = "button" value = "获取选中的文本" onclick="fn3();"/><br />  <br />
    <textarea id="text" cols="50" rows="5">这里是文本框</textarea><br /><br />  
    <input type = "button" value = "插入字符串 {文本2}" onclick="fn2('{文本2}');"/> <input type = "button" value = "获取选中的文本" onclick="fn4();"/><br />  <br /> 
    <div id="editdiv" contentEditable="true">这里是一个可编辑层</div><br />     
</body>  
</html>

  jquery方法

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 在光标定位的地方插入文字的插件</title>
</head>

<body>

<div class="cont">点击我</div><br />
<br />

<textarea class="tarea" name="" cols="50" rows="15">
创作、游戏开发、运营管理等领域的精英人才,并拥有国内多家教育科研机构的战略合作资源。
 
  聚网科技以“为儿童提供真正健康有益的互联网产品”为己任,在产品研发过程中,注重将能力教育融入全新的游戏玩法,不断探索更加受儿童欢迎、更加有益于儿童的多元化娱乐模式,在行业里形成了“锐意进取、不断创新”的良好形象,也使得公司产品一直在行业内保持
</textarea>



<pre>
主要思路: 
  当点击某个元素的时候,让一个输入框,插入指定的值。? 
  1.当点击某个元素的时候,应该让输入框获取焦点,因为只有获得了焦点,才能在里面输入值; 
  IE下:document.selection.createRange() 
  FF下:var start = dthis.selectionStart;    //获取焦点前坐标 
     var end =dthis.selectionEnd;    //获取焦点后坐标 
  2.获取当前输入框焦点的位置 
  3.将值插入到输入框焦点的位置; 
  4.再次获取焦点;保证光标在输入框内
</pre>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
//jQuery 插件

(function($){
    $.fn.extend({
        "insert":function(value){
            //默认参数
            value=$.extend({
                "text":"123"
            },value);
            
            var dthis = $(this)[0]; //将jQuery对象转换为DOM元素
            
            //IE下
            if(document.selection){
                
                $(dthis).focus();        //输入元素textara获取焦点
                var fus = document.selection.createRange();//获取光标位置
                fus.text = value.text;    //在光标位置插入值
                $(dthis).focus();    ///输入元素textara获取焦点
                
            
            }
            //火狐下标准    
            else if(dthis.selectionStart || dthis.selectionStart == '0'){
                
                var start = dthis.selectionStart; 
                var end = dthis.selectionEnd;
                var top = dthis.scrollTop;
                
                //以下这句,应该是在焦点之前,和焦点之后的位置,中间插入我们传入的值
                dthis.value = dthis.value.substring(0, start) + value.text + dthis.value.substring(end, dthis.value.length);
            }
            
            //在输入元素textara没有定位光标的情况
            else{
                this.value += value.text;
                this.focus();    
            };
            
            return $(this);
        }
    })
})(jQuery)
</script>

<script type="text/javascript">
$(function(){
    $(".cont").click(function(){
        $(".tarea").insert({"text":"脚本之家"});
    });
});
</script>

</body>
</html>

  DIV可编辑框鼠标光标处插入图片或者文字

<!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>DIV可编辑框鼠标光标处插入图片或者文字。</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function(){
    $(".imgbox img").click(function(){
    $("#testdiv").focus();
    var sy = $(".imgbox img").index(this) + 1;
    var img_url = "<img src='faceimg/"+sy+".gif'>";
  
/*此处如果不是插入图片可这样:
var img_url = "插入测试的文字";
*/
    _insertimg(img_url);
 
    })
//注:如果要插入的是那种“快捷发言,快捷留言”里的文字,只需把那些文字都分别放在A标签里即可,然后img_url=a标签里面的内容。工作中的编辑器终于搞定!能插入图片和快捷发言和表情图片等。
})
 
 
//监控粘贴(ctrl+v),如果是粘贴过来的东东,则替换多余的html代码,只保留<br>
function pasteHandler(){
setTimeout(function(){
var content = document.getElementById("testdiv").innerHTML;
valiHTML=["br"]; 
content=content.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(/<\/ ?tr[^>]*>/gi, "[br]").replace(/<\/ ?td[^>]*>/gi, "  ").replace(/<(ul|dl|ol)[^>]*>/gi, "[br]").replace(/<(li|dd)[^>]*>/gi, "[br]").replace(/<p [^>]*>/gi, "[br]").replace(new RegExp("<(/?(?:" + valiHTML.join("|") + ")[^>]*)>", "gi"), "[$1]").replace(new RegExp('<span([^>]*class="?at"?[^>]*)>', "gi"), "[span$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:" + valiHTML.join("|") + "|img|span)[^\\]]*)\\]", "gi"), "<$1>");
if(!$.browser.mozilla){
content=content.replace(/\r?\n/gi, "<br>");
}
document.getElementById("testdiv").innerHTML=content;
},1)
  
}
 
//锁定编辑器中鼠标光标位置。。
function _insertimg(str){
var selection= window.getSelection ? window.getSelection() : document.selection;
var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0);
if (!window.getSelection){
document.getElementById('testdiv').focus();
var selection= window.getSelection ? window.getSelection() : document.selection;
var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0);
range.pasteHTML(str);
range.collapse(false);
range.select();
}else{
document.getElementById('testdiv').focus();
range.collapse(false);
var hasR = range.createContextualFragment(str);
var hasR_lastChild = hasR.lastChild;
while (hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") {
var e = hasR_lastChild;
hasR_lastChild = hasR_lastChild.previousSibling;
hasR.removeChild(e)
}                                
range.insertNode(hasR);
if (hasR_lastChild) {
range.setEndAfter(hasR_lastChild);
range.setStartAfter(hasR_lastChild)
}
selection.removeAllRanges();
selection.addRange(range)
}
}
 
//监控按enter键和空格键,如果按了enter键,则取消原事件,用<BR/ >代替。此处还等待修改!!!!!!如果后端能实现各个浏览器回车键产生的P,div, br的输出问题话就无需采用这段JS、
function enterkey(){ 
e = event.keyCode; 
if (e==13||e==32) { 
   var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
   event.returnValue = false;  // 取消此事件的默认操作 
   if(document.selection && document.selection.createRange){
    var myRange = document.selection.createRange();
    myRange.pasteHTML('<br />');
    }else if(window.getSelection){
var selection = window.getSelection();
var range = window.getSelection().getRangeAt(0);
range.deleteContents();
var newP = document.createElement('br');
range.insertNode(newP);
}
//alert(document.getElementById("testdiv").innerHTML)
} 
} 
</script>
<style type="text/css">
.editbox{width:400px;height:200px;border:1px solid #000; overflow-x:hidden; overflow-y:auto; outline:none;}
.editbox img{ margin:0 3px; display:inline;}
</style>
</head> 
<body>
<div id="testdiv" contenteditable="true" class="editbox" onkeydown="enterkey()" >可以在任意文字后面插入图片或者文字哦!<br /></div>
<div class="imgbox">
  <img src="faceimg/1.gif">
  <img src="faceimg/2.gif">
  <img src="faceimg/3.gif">
  <img src="faceimg/4.gif">
</div>
   
        
 
<script type="text/javascript">
//此处必须防止在最下端。
var edt = document.getElementById("testdiv");
if(edt.addEventListener){
edt.addEventListener("paste",pasteHandler,false);
}else{
edt.attachEvent("onpaste",pasteHandler);
}
</script>
</body>
</html>

  

<!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 content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>contenteditable</title>
<style>
*{
    margin:0;padding:0;
}
.im-message-area{
    width:98%;
    padding:2px;
    height:75px;
    border:#000 solid 1px;
    background:#fff;
    font:12px/20px arial,"\5b8b\4f53";
    word-wrap:break-word;
    overflow-y:auto;
    line-height:1;
}
.ul{display:none;}
.ul li{
    background-color:#CCC;
    width:50px;
}
</style>
<script language="javascript" type="text/javascript">
function inimage(text){
    var obj= $(".im-message-area")[0];
    var range, node;
    if(!obj.hasfocus) {
        obj.focus();
    }
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.collapse(false);
        node = range.createContextualFragment(text);
        var c = node.lastChild;
        range.insertNode(node);
        if(c){
            range.setEndAfter(c);
            range.setStartAfter(c)
        }
        var j = window.getSelection();
        j.removeAllRanges();
        j.addRange(range);
        
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().pasteHTML(text);
    }
}
$(document).ready(function(){
    $('#button').click(function(){
        $('.ul').show();
    })
    $('.ul li').each(function(){
        $(this).click(function(){
            inimage($(this).text());
        })    
    })
});

</script>
</head>
<body>
    <div contenteditable="true" id="im_message_area" class="im-message-area"><br></div>
    <a href="javascript:void(0)" id="button">按钮</a>
    <ul class="ul">
        <li>(笑)</li>
        <li>(哭)</li>
        <li>(乐)</li>
    </ul>
</body>
</html>

  

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
    <div id="editor"
        style="width:400px;margin:100px auto;height:300px;border:1px solid #DFDFDF;"
        contenteditable="true">
        这里插入一个图片!将代码中方法document.execCommand(‘InsertImage’, false, _img)更改参数,应该可以插入html代码等其他元素。
    </div>
    <a href="javascript:void(0);" onclick="edit()">强力插入!</a>
    <script>
    var editor = document.getElementById("editor");
    var range, bookmark;
    var saveFocus = function(){//保存焦点状态
        if (document.selection) { //只有坑爹的IE才执行下面的代码
            range = document.selection.createRange();
            bookmark=range.getBookmark();
        }
    }
    editor.onclick = saveFocus;//在鼠标点击编辑区时保存焦点
    editor.onkeydown = saveFocus;//在输入内容时也保存焦点
    function edit() {
        insertImg("http://www.baidu.com/img/baidu_sylogo1.gif");
    }
    function insertImg(_img) {
        if (range) { //同样,坑爹IE专用代码
            range.moveToBookmark(bookmark);
            range.select();
        }
        document.execCommand('InsertImage', false, _img);
 
    }
    </script>
</body>
</html>

  

<html><head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JS设置及获取Textarea的光标位置</title>
  <script>
    var isIE = !(!document.all);
    function posCursor(){
      var start=0,end=0; 
      var oTextarea = document.getElementById("textarea");
      if(isIE){
        //selection 当前激活选中区,即高亮文本块,和/或文当中用户可执行某些操作的其它元素。
        //createRange 从当前文本选中区中创建 TextRange 对象,
        //或从控件选中区中创建 controlRange 集合。
        var sTextRange= document.selection.createRange();

        //判断选中的是不是textarea对象
        if(sTextRange.parentElement()== oTextarea){
          //创建一个TextRange对象
          var oTextRange = document.body.createTextRange();
          //移动文本范围以便范围的开始和结束位置能够完全包含给定元素的文本。
          oTextRange.moveToElementText(oTextarea);
          
          //此时得到两个 TextRange
          //oTextRange文本域(textarea)中文本的TextRange对象
          //sTextRange是选中区域文本的TextRange对象
    
          //compareEndPoints方法介绍,compareEndPoints方法用于比较两个TextRange对象的位置
          //StartToEnd  比较TextRange开头与参数TextRange的末尾。
          //StartToStart比较TextRange开头与参数TextRange的开头。
          //EndToStart  比较TextRange末尾与参数TextRange的开头。
          //EndToEnd    比较TextRange末尾与参数TextRange的末尾。
    
          //moveStart方法介绍,更改范围的开始位置
          //character 按字符移动
          //word       按单词移动
          //sentence  按句子移动
          //textedit  启动编辑动作
    
          //这里我们比较oTextRange和sTextRange的开头,的到选中区域的开头位置
          for (start=0; oTextRange.compareEndPoints("StartToStart", sTextRange) < 0; start++){ 
            oTextRange.moveStart('character', 1); 
          }
          //需要计算一下\n的数目(按字符移动的方式不计\n,所以这里加上) 
          for (var i = 0; i <= start; i ++){
            if (oTextarea.value.charAt(i) == '\n'){ 
              start++; 
            }
          } 
    
          //再计算一次结束的位置
          oTextRange.moveToElementText(oTextarea); 
          for (end = 0; oTextRange.compareEndPoints('StartToEnd', sTextRange) < 0; end ++){
            oTextRange.moveStart('character', 1);
          }
          for (var i = 0; i <= end; i ++){
            if (oTextarea.value.charAt(i) == '\n'){ 
              end++; 
            }
          }
        }
      }else{
        start = oTextarea.selectionStart;
        end = oTextarea.selectionEnd;
      }
      document.getElementById("start").value = start; 
      document.getElementById("end").value = end;
    }
    
    
    function moveCursor(){
      var oTextarea = document.getElementById("textarea");
      var start = parseInt(document.getElementById("start").value); 
      var end =  parseInt(document.getElementById("end").value);
      if(isNaN(start)||isNaN(end)){
        alert("位置输入错误");
      }
      if(isIE){
        var oTextRange = oTextarea.createTextRange();
        var LStart = start;
        var LEnd = end;
        var start = 0;
        var end = 0;
        var value = oTextarea.value;
        for(var i=0; i<value.length && i<LStart; i++){
          var c = value.charAt(i);
          if(c!='\n'){
            start++;
          }
        }
        for(var i=value.length-1; i>=LEnd && i>=0; i--){
          var c = value.charAt(i);
          if(c!='\n'){
            end++;
          }
        }
        oTextRange.moveStart('character', start);
        oTextRange.moveEnd('character', -end);
        //oTextRange.collapse(true);
        oTextRange.select();
        oTextarea.focus();
      }else{
        oTextarea.select();
        oTextarea.selectionStart=start;
        oTextarea.selectionEnd=end;
      }
    } 
  </script>
  <body>
    <table border="1" cellspacing="0" cellpadding="0"> 
      <tr> 
        <td>start: <input type="text" id="start" size="3" value="0"/></td> 
        <td>end:   <input type="text" id="end"   size="3" value="0"/></td> 
      </tr> 
      <tr> 
      <td colspan="2"> 
        <textarea id="textarea"
          onKeydown="posCursor()" 
          onKeyup="posCursor()" 
          onmousedown="posCursor()" 
          onmouseup="posCursor()" 
          onfocus="posCursor()" 
          rows="14"
          cols="50">虞美人
春花秋月何时了,往事知多少。
小楼昨夜又东风,故国不堪回首月明中!
雕l栏玉砌应犹在,只是朱颜改。
问君能有几多愁?恰似一江春水向东流。</textarea> 
        </td> 
      </tr> 
      <tr> 
        <td></td> 
        <td><input type="button" onClick="moveCursor()" value="设置光标位置"/></td> 
      </tr> 
    </table> 
  </body>
</html>

  

<!DOCTYPE html>
<html>
<head>
<title>js获取div编辑框,textarea,input text的光标位置,兼容FF和IE</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
function getPosition(element) {
    var OsObject = "";
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        OsObject = "MSIE";
    }
    if (navigator.userAgent.indexOf("Firefox") > 0) {
        OsObject = "Firefox";
    }
    if (navigator.userAgent.indexOf("Safari") > 0) {
        OsObject = "Safari";
    }
    if (navigator.userAgent.indexOf("Camino") > 0) {
        OsObject = "Camino";
    }
    if (navigator.userAgent.indexOf("Gecko") > 0) {
        OsObject = "Gecko";
    }
    if (navigator.userAgent.indexOf("Chrome") > 0) {
        OsObject = "Chrome";
    }

    var result = 0;
    if (!document.selection) { //非IE浏览器
        var thisTagName = null;
        if ((element.tagNam!= "TEXTAREA") && (element.tagNam != "INPUT")){
            if (element.tagName == "DIV" && element.getAttribute("contenteditable") == "true") {
                thisTagName = window.getSelection().anchorNode.parentElement.tagName;
            } else {
                thisTagName == null;
            }
        } else {
            if (element.tagNam == "INPUT" && element.getAttribute("type") == "text") {
                thisTagName = window.getSelection().anchorNode.tagName;
            } else {
                console.log(window.getSelection());
                thisTagName = window.getSelection().anchorNode.tagName;
            }
        }
        if (thisTagName == "TEXTAREA" || thisTagName == "INPUT" || (thisTagName == "BODY" && OsObject == "Chrome")) {
            result = element.selectionStart
        } else if (thisTagName != null) {
            if (thisTagName == element.tagName) {
                if (window.getSelection().anchorNode.textContent == element.innerHTML) {
                    result = window.getSelection().anchorOffset;
                } else {
                    var currentIndex = window.getSelection().anchorOffset;
                    var txt = "";
                    var txtoo = window.getSelection().anchorNode.previousSibling;
                    while (txtoo != null) {
                        txt += txtoo.textContent;
                        txtoo = txtoo.previousSibling;
                    }
                    result = txt.length + currentIndex;
                }
            } else {
                var currentIndex = window.getSelection().anchorOffset;
                var txt = "";
                var txtoo = window.getSelection().anchorNode.parentElement.previousSibling;
                while (txtoo != null) {
                    txt += txtoo.textContent;
                    txtoo = txtoo.previousSibling;
                }
                result = txt.length + currentIndex;
            }
        } else {
            return 0;
        }
    } else { //IE
        var rng;
        if (element.tagNam == "TEXTAREA" || (element.tagNam == "INPUT" && element.getAttribute("type") == "text") || (element.tagName == "DIV" && element.getAttribute("contenteditable") == "true")) {
            element.focus();
            rng = document.selection.createRange();
            rng.moveStart('character', -element.innerText.length);
            var text = rng.text;
            for (var i = 0; i < element.innerText.length; i++) {
                if (element.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) {
                    result = i + 1;
                }
            }
        } else {
            return 0;
        }
    }
    return result;
}

function getValue(element) {
    var pos = getPosition(element);
    document.getElementById("pnum").value = pos;
}
</script>
<style type="text/css">
#Div1, #Div2{
    width: 500px;
    height: 100px;
    border: solid 1px black;
}
</style>
</head>
<body>
    <input id="pnum" type="text" value="Hello,wellcome to test! 你好,欢迎测试!" onmouseup="getValue(this)" style="display: block" />
    <textarea cols="60" rows="10" onkeyup="getValue(this)" onmouseup="getValue(this)">
        Hello,wellcome to test! 你好,欢迎测试!      注意源代码开闭合标记之间不能换行,否则统计错误!
    </textarea>
    <div id="Div1" onclick="getValue(this);" onkeyup="getValue(this);" contenteditable="true">
        一二三
        <span>四五</span>
        六七八
        <span>九零</span> 
        注意源代码开闭合标记之间不能换行,否则统计错误!注意div编辑框源码里面是嵌套有其他标签的,可以正常返回正确位置!
    </div>
    <br />
</body>
</html>

  

原生js的方法:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
 
<body>
 
 
 
<script   type="text/javascript">  
function setCaret(textObj) {
    if (textObj.createTextRange) {
        textObj.caretPos = document.selection.createRange().duplicate();
    }
}
function insertAtCaret(textObj, textFeildValue) {
    if (document.all) {
        if (textObj.createTextRange && textObj.caretPos) {
            var caretPos = textObj.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '   ' ? textFeildValue + '   ' : textFeildValue;
        } else {
            textObj.value = textFeildValue;
        }
    } else {
        if (textObj.setSelectionRange) {
            var rangeStart = textObj.selectionStart;
            var rangeEnd = textObj.selectionEnd;
            var tempStr1 = textObj.value.substring(0, rangeStart);
            var tempStr2 = textObj.value.substring(rangeEnd);
            textObj.value = tempStr1 + textFeildValue + tempStr2;
        } else {
            alert("This   version   of   Mozilla   based   browser   does   not   support   setSelectionRange");
        }
    }
}  
 </script> 
    
  <form   id="form1"   action=""   onsubmit=""   method="post"   enctype="text/plain">   
  <p> 
  <textarea   name="tarea"   rows=""   cols=""   style="width:300px;height:120px;" 
  onselect="setCaret(this);" 
  onclick="setCaret(this);" 
  onkeyup="setCaret(this);"   >例子例子例子例子例子</textarea> 
  <br/><br/> 
  <input   type="text"   name="textfield"   style="width:220px;"   value="插入FireFox"/> 
  <br/> 
  <input   type="button"   value="插入" 
  onclick="insertAtCaret(this.form.tarea,this.form.textfield.value);"/> 
  </p> 
  </form>  
 
 
<div id="box" contenteditable="true" style="border:1px solid #ccc; width:300px; height:200px;">sljfldjfldf</div>
 
</body>
</html>
posted @ 2019-03-01 15:46  ·悟空·  阅读(7998)  评论(0编辑  收藏  举报