在实际开发中,不难发现的是,客户端JavaScript编程中的很多不兼容性都是针对IE的,这就导致需要按照一定的规则去为IE编写代码,而用另外一种方式去为其他浏览器编码。

1. 扩展兼容性

通用的方式是用if…else…语句来扩展兼容性,如

if(element.addEventListener){
	//可使用该W3C方法的浏览器的相关处理
}
else if (element.attachEvent){
	//IE浏览器的相关处理
}
else{
	//除此之外的处理
}

除此之外,IE浏览器支持条件注释,尽管不符合标准规范,但在处理不兼容性时非常有用。HTML中的条件注释如下。

<!-- [if IE 6 ]>
This content is actually inside an HTML comment.
It will only be displayed in IE 6.
<! [endif]-->

<!-- [if lte IE 7 ]>
This content will only be displayed by IE 5, 6 and 7 and earlier.
lte stands for "less than or equal". You can also use "lt","gt" and "gte".
<! [endif]-->

<!-- [if ! IE ]><-->
This is normal HTML content, but IE will not display it
because of the comment above and the comment below.
<!--><! [endif]-->
This is normal content, displayed by all browsers.

IE的JavaScript解释器也支持条件注释,以文本 /*@cc_on 开头,以文本 @*/结尾,通过条件注释和常规的JavaScript注释的合理交叉组合,可以设置在IE中运行一段代码而在其他浏览器中用运行一段不同的代码。

/*@cc_on
	@if(@_jscript)
		alert("You are using IE");
	@else*/
		alert("You are not using IE");
	/*@end
@*/

2.IE浏览器版本切换进行测试

进入开发人员工具后,可在上方菜单栏处切换IE版本,详见下图。
IE浏览器调试Javascript

相关文章:

  • 2021-10-16
  • 2021-10-25
  • 2021-07-30
  • 2021-04-19
  • 2021-12-24
  • 2021-07-25
  • 2021-05-18
  • 2022-12-23
猜你喜欢
  • 2021-09-07
  • 2021-07-18
  • 2021-11-12
  • 2022-12-23
  • 2021-05-27
  • 2022-12-23
  • 2021-07-06
相关资源
相似解决方案