viviier

Javascript 兼容写法

事件 兼容写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var EventUtil = {
// 添加函数
addHandlder: function(elm, type, handler) {
if(typeof addEventListener != 'undefined') {
createHandler = function() {
return elm.addEventListener(type, handler);
}
} else if(typeof attachEvent != 'undefined') {
createHandler = function() {
return elm.attachEvent('on' + type, handler);
} else {
createHandler = function() {
return elm['on' + type] = handler;
}
}
}
return createHandler();
},
// event
getEvent: function(event) {
return event ? event || window.event;
},
// target
getTarget: function(event) {
return event.target || event.srcElement;
},
// preventDefault
preventDefault: function(event) {
if(event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
// stopPropagation
stopPropagation: function(event) {
if(event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
}


Ajax 兼容写法
1
2
3
4
5
6
7
8
9
10
11
var createXHR = (function() {
if(typeof XMLHttpRequest != 'undefined') {
return function() {
return new XMLHttpRequest();
}
} else if(typeof ActiveXObject != 'undefined') {
return function() {
return new ActiveXObject('MSXML2.XMLHttp');
}
}
})();
tips
1
2
3
4
5
6
7
8
9
// 重复定时器,解决setInterval的一些小问题
setTimeout(function() {
var box = document.getElementById('box');
left = parseInt(box.style.left ? box.style.left : box.offsetLeft) + 5;
box.style.left = left + 'px';
if(left < 200) {
setTimeout(arguments.callee, 50);
}
}, 50);
------本文结束感谢阅读------