昨天有人问我这个事,今天就来做做了,最开始是按自己的思路做,在keyup事件里对输入键做判断,以处理什么退格啊,删除啊,上下左右移动等动作,然后记录光标位置来做文本处理,费了好大劲。不过后来无意中发现了【孟子E章】的一个解决方案,简洁有效。
本着研究学习的目的,我对【孟子E章】的方法做了个封装,这样在使用时会简单一些,尤其是需要插入的标签较多时。
这是调用代码:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="/1999/xhtml">
<headrunat="server">
<title>无标题页</title>
<scripttype="text/javascript"src="JScript.js"></script>
<scripttype="text/javascript">
window.onload=function()
{
varci=newCursorInsert();
ci.SetTargetTextControl(document.getElementById('txtContent'));
ci.SetSourceControl(document.getElementById('btnSource'),'[note]NOTE[/note]');
ci.Initialize();
}
</script>
</head>
<body>
<formid="form1"runat="server">
<textareaid="txtContent"cols="1"rows="1"style="width:500px;height:300px;"></textarea><br/>
<inputid="btnSource"type="button"value="Clickme"/>
</form>
</body>
</html>
这是封装后的类:
varCursorInsert=function()
{
this.targetTextControl=null;
this.sourceControls=newArray();
this.SetTargetTextControl=function(ctrl)
{
this.targetTextControl=ctrl;
}
this.SetSourceControl=function(ctrl,value)
{
this.sourceControls[this.sourceControls.length]={"Button":ctrl,"Value":value};
}
this.Initialize=function()
{
if(this.targetTextControl==null)
{
alert("Pleasesettargettextcontrolfirst!");
return;
}
if(this.sourceControls.length==0)
{
alert("Pleasesetsourcecontrolfirst!");
return;
}
this.SetText(this.targetTextControl);
for(vari=0;i<this.sourceControls.length;i++)
{
this.SetButton(this.sourceControls[i].Button,this.sourceControls[i].Value,this.targetTextControl);
}
}
this.SetButton=function(btn,value,target)
{
varctrl=target==null?this.TextControl:target;
btn.onclick=function()
{
CursorInsert.prototype.InsertAtCaret(target,value);
}
}
this.SetText=function(ctrl)
{
ctrl.onselect=function()
{
CursorInsert.prototype.SetCaret(this);
}
ctrl.onclick=function()
{
CursorInsert.prototype.SetCaret(this);
}
ctrl.onkeyup=function()
{
CursorInsert.prototype.SetCaret(this);
}
}
}
CursorInsert.prototype.SetCaret=function(textObj)
{
if(textObj.createTextRange)
{
textObj.caretPos=document.selection.createRange().duplicate();
}
}
CursorInsert.prototype.InsertAtCaret=function(textObj,value)
{
if(document.all)
{
if(textObj.createTextRange&&textObj.caretPos)
{
varcaretPos=textObj.caretPos;
caretPos.text=caretPos.text.charAt(caretPos.text.length-1)==''?value+'':value;
}
else
{
textObj.value=value;
}
}
else
{
if(textObj.setSelectionRange)
{
varrangeStart=textObj.selectionStart;
varrangeEnd=textObj.selectionEnd;
vartempStr1=textObj.value.substring(0,rangeStart);
vartempStr2=textObj.value.substring(rangeEnd);
textObj.value=tempStr1+value+tempStr2;
}
else
{
alert("ThisversionofMozillabasedbrowserdoesnotsupportsetSelectionRange!");
}
}
}