IE 与其它浏览器兼容性

rem

IE6~8 不支持rem,解决用 css hack:width:25%\9

移动端用rem

移动端 css像素和物理像素不对等,可能1个css像素对应4个物理像素,不同设备像素不同。为了解决这个问题,用rem。

根部font-size根据设备不同屏幕宽度计算不同字号大小。

1.JS动态计算(常见做法)

1
2
3
4
5
6
1. 定基准值,设计稿是750宽度(2倍屏),字体的大小是24px.

2. 计算指定宽度的字体大小。
window.onload = function(){
document.documentElement.style.fontSize = document.documentElement.clientWidth / 24 + 'px';
}
  1. 根据dpr设定 (比较好的做法)ps : 一般时初始化时设置为根元素html的attribute,
1
window.document.documentElement.setAttribute('dpr',window.devicePixelRatio)

然后css这样写

1
2
3
4
5
6
7
[dpr=1] {
font-size=16px;
}

[dpr=2] {
font-size=32px;
}

css ie 条件注释

IE条件注释 (conditional comment) 是于HTML源码中被IE有条件解释的语句。条件注释可被用来向IE提供及隐藏代码,注意:只有 IE9以下的浏览器才能识别这种语法,其他浏览器仅仅认为是普通注释。

注意: if IE 6 中 IE 和 6 的空格不能省,不然会显示在页面上。

1
2
3
4
5
6
7
8
9
<!--[if IE 6]>  
<p>IE6下 这句生效,在其他浏览器下认为是普通注释</p>
<![endif]-->
<!--[if !IE]><!-->
<script>alert("在 IE 下条件语法生效,但script不执行。在非 IE 下上下两句都被当做注释所以当前 script 会执行");</script>
<!--<![endif]-->
<!--[if IE 8]>
<link href="ie8only.css" rel="stylesheet">
<![endif]-->

各浏览器默认属性不同

reset 或 normalize.css

ie6 双倍margin

设置display:inline

css hack

1
2
3
* IE6识别
_ IE6、7识别
\9 IE9以下

attachEvent 和 addEventListener

1
2
3
4
5
6
- target.addEventListener(type, listener, useCapture); 
- target: 文档节点、documentwindow 或 XMLHttpRequest。
- type: 字符串,事件名称,不含“on”,比如“click”、“mouseover”、“keydown”等。
- listener :实现了 EventListener 接口或者是 JavaScript 中的函数。
- useCapture :是否使用捕捉,一般用 false
例如:document.getElementById("testText").addEventListener("keydown", function (event) { alert(event.keyCode); }, false);

IE中:

1
2
3
4
5
target.attachEvent(type, listener); 
target: 文档节点、documentwindow 或 XMLHttpRequest。
type: 字符串,事件名称,含“on”,比如“onclick”、“onmouseover”、“onkeydown”等。
listener :实现了 EventListener 接口或者是 JavaScript 中的函数。
例如:document.getElementById("txt").attachEvent("onclick",function(event){alert(event.keyCode);});

W3C 及 IE 同时支持移除指定的事件, 用途是移除设定的事件, 格式分别如下:

1
2
3
4
5
6
7
W3C格式: 

removeEventListener(event,function,capture/bubble);

Windows IE的格式如下:

detachEvent(event,function);

阻止事件冒泡,使成为捕获型事件触发机制

1
2
3
4
5
6
7
8
9
function stopBubble(e) { 
//如果提供了事件对象,则这是一个非IE浏览器
if ( e && e.stopPropagation )
//因此它支持W3C的stopPropagation()方法
e.stopPropagation();
else
//否则,我们需要使用IE的方式来取消事件冒泡
window.event.cancelBubble = true;
}

停止默认事件默认行为

1
2
3
4
5
6
7
8
9
10
//阻止浏览器的默认行为 
function stopDefault( e ) {
//阻止默认浏览器动作(W3C)
if ( e && e.preventDefault )
e.preventDefault();
//IE中阻止函数器默认动作的方式
else
window.event.returnValue = false;
return false;
}

创建XMLHttpRequest

1
2
3
4
5
6
//创建 - 非IE6 - 第一步
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本浏览器
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}