现在的位置: 首页 > 综合 > 正文

在线编辑器–(4)TAB键缩进功能

2012年03月20日 ⁄ 综合 ⁄ 共 6306字 ⁄ 字号 评论关闭
利用IE的DHTML属性给编辑器增加了TAB键缩进功能.基本原理是:通过监听键盘的keydown事件,来取消浏览器默认事件,并在光标所在处增加"\t\t\t".来实现缩进上.

实现的JS代码如下:

window.onload=function(){
 initDocument();
 initFormat();
 var editor=document.getElementById("editor_position").contentWindow;
 //获取按键事件的方法1
 if(document.all){//IE
  editor.document.attachEvent("onkeydown",keyPress1);
 }else{//other
  editor.document.addEventListener("keydown",keyPress1,false)
 }
 //获取按键事件的方法2
 /*editor.document.body.onkeypress=function(){
  var editor=document.getElementById("editor_position").contentWindow;
  return keyPress2(editor.event);
 }*/
 
}
//对应于按键事件方法1
function keyPress1(event){
 //当按下TAB键时,通过取消默认事件,并动态输入四个\t来实现TAB键缩进.
 if(event.keyCode==9){
  //取消默认事件
  if(document.all){//IE
   event.returnValue=false;
  }else{//other(FF)
   event.preventDefault();
  }
  var editor=document.getElementById("editor_position").contentWindow;
  if(document.all){//IE
   var rng=editor.document.selection.createRange();
   rng.text="\t\t\t";
   //rng.collapse(false);
   //rng.select();
  }else{//FF
   var range=document.createRange();
   range.text="ok";
   var rng=editor.window.getSelection();
   if(rng.rangeCount>0)rng.removeAllRanges();
   rng.text="dovapour";
  }
 }
}
/*
IE中:keypress事件的keyCode能区分大小写,但不能识别功能键(Ctr,Shift,Alt等); keyup和keydown事件的keyCode不能区分大小写,能识别功能键.
FF中:keypress事件的keyCode=0; keyup和keydown事件的keyCode不能区分大小写,能识别功能键.
Chrome中:keypress事件的keyCode能区分大小写,但不能识别功能键(Ctr,Shift,Alt等); keyup和keydown事件的keyCode不能区分大小写,能识别功能键.
*/

完整可运行代码如下:你也可以修改代码后再运行.

抱歉!评论已关闭.