Javascriptで編集枠とTextAreaのカーソルに文字を挿入し、連続挿入をサポートします.

2909 ワード

<html>

<head>

<title>Test of inserting characters at cursor position</title>

<script type="text/javascript" src="jquery.pack.js"></script>

<script>

function setCaret(textObj){  

  if(textObj.createTextRange){    

    textObj.caretPos=document.selection.createRange().duplicate();    

  }  

}

function insertAtCaret(textObj,textFeildValue){  

  if(document.all&&textObj.createTextRange&&textObj.caretPos){       

      var caretPos=textObj.caretPos;      

      caretPos.text=caretPos.text.charAt(caretPos.text.length-1)==''?textFeildValue+'':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;

      textObj.focus();

      var len=textFeildValue.length;

      textObj.setSelectionRange(rangeStart+len,rangeStart+len);

      textObj.blur();

  }else {

    textObj.value+=textFeildValue;

  } 

} 

$(document).ready(function(){

   if($.browser.msie){

     $("#tag")

       .click(function(){

         setCaret($(this).get(0));

       })

       .select(function(){

         setCaret($(this).get(0));

       })

       .keyup(function(){

         setCaret($(this).get(0));

       });

       $("#tagA")

       .click(function(){

         setCaret($(this).get(0));

       })

       .select(function(){

         setCaret($(this).get(0));

       })

       .keyup(function(){

         setCaret($(this).get(0));

       });

   }

   $("a.insertTag")

     .click(function(){

       insertAtCaret($("#tag").get(0),$(this).html());

     });

    $("a.insertTagA")

     .click(function(){

       insertAtCaret($("#tagA").get(0),$(this).html());

     });

 });

</script>

</head>

<body>

References:<br/>

http://www.dnew.cn/post/287.htm<br/>

http://blog.vishalon.net/Post/57.aspx

  <div>

    <form>

    <input type="text" id="tag" value="testtesttest" size="50" /><br/>

    <a class="insertTag" href="javascript:void(0)">tag1</a>

    <a class="insertTag" href="javascript:void(0)">tag2</a>

    <br/>

    <textarea id="tagA" style="width:300px;height:120px;" >tttttt tttt</textarea><br/>

    <a class="insertTagA" href="javascript:void(0)">tag3</a>

    <a class="insertTagA" href="javascript:void(0)">tag4</a>

    </form>

    

  </div>

</body>

</html>