跨浏览器开发经验总结(三) 警惕“IE依赖综合症”

DHTML

  DHTML是个好东西,大大方面了前端的交互实现,使得获取页面元素以及动态修改页面元素变的简单无比。但是所有的浏览器都认识这些语法吗?

  document.all

  document.all不是所有浏览器都能识别,要写出更通用的代码,最好还是通过id来得到,使用document.getElementById(…)

  element.outerText, element.innerText, element.outerHTML,element.innerHTML

  element.outerText, element.innerText, element.outerHTML是属于IE特有的, 而element.innerHTML是通用的。

  如果要在其他浏览器下使用不通用的属性,可以参考以下代码实现:

  

复制代码 代码如下:

  if(!isIE()){

  HTMLElement.prototype.__defineGetter__("innerText",

  function(){

  var anyString = "";

  var childS = this.childNodes;

  for(var i=0; i<childS.length; i++){

  if(childS[i].nodeType==1)

  anyString += childS[i].innerText;

  else if(childS[i].nodeType==3)

  anyString += ahildS[i].nodeValue;

  }

  return anyString;

  }

  );

  HTMLElement.prototype.__defineSetter__("innerText",

  function(sText){

  this.textContent=sText;

  }

  );

  }

  document.forms.actionForm.inputName.value

  之前用document.all.title.value来获取名为actionForm的标单中名为title的input域值得地方,应该改为document.forms.actionForm.input.value,要这么使用,首先要保证HTML中form标签与其他标签结构上有完整的闭合关系。

  Table操作

  moveRow ( iSource , iTarget )方法

  oRow = tableObject.moveRow ( iSource , iTarget ),这个方法可以很方便实现table中tr的动态顺序调整。但是这个方法是IE内核自己实现的,不是DOM标准方法,所以别的浏览器没有。在使用到了这些IE独有的方法的地方,要么换用标准的DOM节点操纵方式——insertBefore(currobj, beforeObj.nextSibling),要么先在HTMLDocument类的prototype上自己实现一个 moveRow方法:

  

复制代码 代码如下:

  function getTRArray(){

  ……

  //将需要操纵的tr都放入数组作为该方法的返回值

  }

  function getTRByIndex(sourceELIndex){

  var trArray = getTRArray();

  var result = trArray[sourceELIndex];

  return result;

  }

  if( !isIE && HTMLElement.moveRow == null )

  {

  //入参说明:

  //sourceELIndex :需要移动的tr在tbody中的第几行(>=1)

  //targetELIndex :需要移动到tbody中的第几行(>=1,<=行数)

  HTMLElement.prototype.moveRow = function(sourceELIndex,targetELIndex)

  {

  var tbObject = document.getElementById("tbodyEL");

  var resultEL;

  if(sourceELIndex>=targetELIndex)

  {//move up

  var s = sourceELIndex-1;

  var t = targetELIndex-1;

  }else{

  var s = sourceELIndex-1;

  var t = targetELIndex;

  }

  var sourceEL = getTRByIndex(s);

  var targetEL = getTRByIndex(t);

  //alert("begin"+sourceELIndex+targetELIndex);

  //alert("begin"+s+t);

  tbObject.insertBefore(sourceEL,targetEL);

  resultEL = sourceEL;

  return resultEL;

  }

  }