JAVASCRIPT 浏览器兼容性问题及解决方案列表

原文链接http://www.javaarch.net/jiagoushi/611.htm

JAVASCRIPT 浏览器兼容性问题及解决方案列表
(1)获取HTML元素
只兼容IE:
document.all.hello 
hello 
兼容所有: 
document.getElementById(“hello ”) 以ID来访问对象,且一个ID在页面中必须是唯一document.getElementsByTagName(“div”)[0] 以标签名来访问对象
document.getElementsByName("inputName")[1]

(2)获取FORM表单元素
只兼容IE: 
document.formname.itemname  
兼容所有:
document.forms[“formName”].elements[“itemname”]。
document.forms[i].elements[“itemname”] 

(3)设置CSS
只兼容FireFox: 
obj.setAttribute(style,color:green) 
兼容所有:
document.getElementById("banana").className
 document.getElementById("banana").style.color 
document.getElementById("banana").onclick document.getElementById("banana").class="fruit" document.getElementById("banana").style.color="blue" document.getElementById("banana").onclick= function (){alert("我是香蕉")} 

(4)设置长宽高
只兼容IE: 
obj.style.height = imgObj.height  
兼容所有:
obj.style.height = imgObj.height + 'px';

(5)obj.innerText

只兼容IE: 
obj.innerText= "myText";
兼容所有:

 if (document.all) {
    obj.innerText = "myText";
}
else {
    obj.textContent = "myText";
}

(6)Firefox下的onload问题 
只兼容IE: 
function over(){ 
alert("页面加载完毕") 
} 
document.body.onload= over 

兼容所有:

window.onload=over

(7)打开窗口
只兼容IE: 
IE中可以通过showModalDialog和showModelessDialog打开模态和非模态窗口
兼容所有:
直接使用window.open(pageURL,name,parameters)方式打开新窗口。
如果需要传递参数,可以使用frame或者iframe。


(8)获取Frame对象

只兼容IE:
var frame1 = window.testFrame
兼容所有:
window.top.document.getElementById("frameId")来访问frame标签
并且可以通过window.top.document.getElementById("testFrame").src = 'xx.htm'来切换frame的内容
也都可以通过window.top.frameName.location = 'xx.htm'来切换frame的内容

(9)变量名与某 HTML 对象 id 相同的问题

IE中对象 对象ID不能与HTML对象的ID同名。而Firefox可以。

兼容所有:
在声明变量时,一律加上 var ,以避免歧义,这样在 IE 中亦可正常运行。
  此外,最好不要取与 HTML 对象 id 相同的变量名,以减少错误。