JavaScript脚本 按tab键在光标处插入空格
发布网友
发布时间:2022-05-16 15:15
我来回答
共2个回答
热心网友
时间:2022-05-16 16:45
经测试IE通过,以下代码仅供参考,有疑问请me我:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language="javascript">
<!--
function getCursorPsn(txb)
{
var slct = document.selection;
var rng = slct.createRange();
txb.select();
rng.setEndPoint("StartToStart", slct.createRange());
var psn = rng.text.length;
rng.collapse(false);
rng.select();
return psn;
}
function focusEnd(obj,position)
{
obj.focus();
try
{
var rng = obj.createTextRange();
rng.moveEnd("character",position);
rng.moveStart("character",position);
rng.collapse(true);
rng.select();
}
catch(e)
{
}
};
function insertTab(obj,event){
if(event.keyCode==9){
event.returnValue=false;
var position = getCursorPsn(obj);
var tr=document.selection.createRange();
tr.text = " ";
tr.collapse(false);
tr.select();
focusEnd(obj,position+1);
return false;
}
}
//-->
</script>
</HEAD>
<BODY>
<INPUT TYPE="text" NAME="" size="50" onkeydown ="insertTab(this,event);">
<TEXTAREA NAME="" ROWS="10" COLS="50" onkeydown ="insertTab(this,event);"></TEXTAREA>
</BODY>
</HTML>