在线编辑器--(4)TAB键缩进功能- {wz}之心- 博客园
利用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不能区分大小写,能识别功能键.
*/


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


posted on 2010-02-06 10:38 阅读(7)   所属分类:

郑重声明:资讯 【在线编辑器--(4)TAB键缩进功能- {wz}之心- 博客园】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——