跨瀏覽器開發(fā)經(jīng)驗(yàn)總結(jié)(三) 警惕“IE依賴綜合癥”
2024-05-06 14:10:03
供稿:網(wǎng)友
DHTML
DHTML是個(gè)好東西,大大方面了前端的交互實(shí)現(xiàn),使得獲取頁面元素以及動(dòng)態(tài)修改頁面元素變的簡(jiǎn)單無比。但是所有的瀏覽器都認(rèn)識(shí)這些語法嗎?
document.all
document.all不是所有瀏覽器都能識(shí)別,要寫出更通用的代碼,最好還是通過id來得到,使用document.getElementById(…)
element.outerText, element.innerText, element.outerHTML,element.innerHTML
element.outerText, element.innerText, element.outerHTML是屬于IE特有的, 而element.innerHTML是通用的。
如果要在其他瀏覽器下使用不通用的屬性,可以參考以下代碼實(shí)現(xiàn):
代碼如下:
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的標(biāo)單中名為title的input域值得地方,應(yīng)該改為document.forms.actionForm.input.value,要這么使用,首先要保證HTML中form標(biāo)簽與其他標(biāo)簽結(jié)構(gòu)上有完整的閉合關(guān)系。
Table操作
moveRow ( iSource , iTarget )方法
oRow = tableObject.moveRow ( iSource , iTarget ),這個(gè)方法可以很方便實(shí)現(xiàn)table中tr的動(dòng)態(tài)順序調(diào)整。但是這個(gè)方法是IE內(nèi)核自己實(shí)現(xiàn)的,不是DOM標(biāo)準(zhǔn)方法,所以別的瀏覽器沒有。在使用到了這些IE獨(dú)有的方法的地方,要么換用標(biāo)準(zhǔn)的DOM節(jié)點(diǎn)操縱方式——insertBefore(currobj, beforeObj.nextSibling),要么先在HTMLDocument類的prototype上自己實(shí)現(xiàn)一個(gè) moveRow方法:
代碼如下:
function getTRArray(){
……
//將需要操縱的tr都放入數(shù)組作為該方法的返回值
}
function getTRByIndex(sourceELIndex){
var trArray = getTRArray();
var result = trArray[sourceELIndex];
return result;
}
if( !isIE && HTMLElement.moveRow == null )
{
//入?yún)⒄f明:
//sourceELIndex :需要移動(dòng)的tr在tbody中的第幾行(>=1)
//targetELIndex :需要移動(dòng)到tbody中的第幾行(>=1,<=行數(shù))
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;