首页 > 开发 > Javascript > 正文

JavaScript在IE和Firefox(火狐)的不兼容问题解决方法小结

2020-02-28 04:06:52
字体:
来源:转载
供稿:网友
1.兼容firefox的 outerHTML,FF中没有outerHtml的方法。
代码如下:
if (window.HTMLElement) {
HTMLElement.prototype.__defineSetter__("outerHTML",function(sHTML) {
var r=this.ownerDocument.createRange();
r.setStartBefore(this);
var df=r.createContextualFragment(sHTML);
this.parentNode.replaceChild(df,this);
return sHTML;
});
HTMLElement.prototype.__defineGetter__("outerHTML",function() {
var attr;
var attrs=this.attributes;
var str="<"+this.tagName.toLowerCase();
for (var i=0;i<attrs.length;i++) {
attr=attrs[i];
if(attr.specified)
str+=" "+attr.name+'="'+attr.value+'"';
}
if(!this.canHaveChildren)
return str+">";
return str+">"+this.innerHTML+"</"+this.tagName.toLowerCase()+">";
});
HTMLElement.prototype.__defineGetter__("canHaveChildren",function() {
switch(this.tagName.toLowerCase()) {
case "area":
case "base":
case "basefont":
case "col":
case "frame":
case "hr":
case "img":
case "br":
case "input":
case "isindex":
case "link":
case "meta":
case "param":
return false;
}
return true;
});
}

2.集合类对象问题
说明:IE下,可以使用()或[]获取集合类对象;Firefox下,只能使用[]获取集合类对象.
解决方法:统一使用[]获取集合类对象.
3.自定义属性问题
说明:IE下,可以使用获取常规属性的方法来获取自定义属性,也可以使用getAttribute()获取自定义属性;Firefox下,只能使用getAttribute()获取自定义属性.
解决方法:统一通过getAttribute()获取自定义属性.

4.eval("idName")问题
说明:IE下,,可以使用eval("idName")或getElementById("idName")来取得id为idName的HTML对象;Firefox下只能使用getElementById("idName")来取得id为idName的HTML对象.
解决方法:统一用getElementById("idName")来取得id为idName的HTML对象.
5.变量名与某HTML对象ID相同的问题
说明:IE下,HTML对象的ID可以作为document的下属对象变量名直接使用;Firefox下则不能.Firefox下,可以使用与HTML对象ID相同的变量名;IE下则不能。
解决方法:使用document.getElementById("idName")代替document.idName.最好不要取HTML对象ID相同的变量名,以减少错误;在声明变量时,一律加上var,以避免歧义.
6.const问题
说明:Firefox下,可以使用const关键字或var关键字来定义常量;IE下,只能使用var关键字来定义常量.
解决方法:统一使用var关键字来定义常量.
7.input.type属性问题
说明:IE下input.type属性为只读;但是Firefox下input.type属性为读写.
8.window.event问题
说明:window.event只能在IE下运行,而不能在Firefox下运行,这是因为Firefox的event只能在事件发生的现场使用.
解决方法:
IE:
代码如下:
<input name="Button8_1" type="button" value="IE" onclick="javascript:gotoSubmit8_1()"/>
...
<script language="javascript">
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表