日期:2014-05-16  浏览次数:20392 次

JS 文本框光标处插入特定字符
<%@ Page Language="C#" AutoEventWireup="true" AspCompat="true" CodeBehind="WebForm1.aspx.cs"
    Inherits="SJLERP.WebForm1" %>


<!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">
<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);"   >例子例子例 Forget Never  www.52mvc.com 社区 子例子例子 asp.net </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> 
</html>