常用兼容方法
1.总结事件兼容
var EventUtil = { addHandler: function (element, type, handler) {//添加监听事件兼容 if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) {//兼容ie element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, getEvent: function (event) {//event兼容 return event ? event : window.event; }, getTarget: function (event) {//获取当前目标元素 return event.target || event.srcElement; }, preventDefault: function (event) {//阻止默认事件兼容 if (event.preventDefault) { event.preventDefault(); } else {//兼容ie event.returnValue = false; } }, removeHandler: function (element, type, handler) {//移除监听事件兼容 if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) {//兼容ie element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } }, stopPropagation: function (event) {//阻止事件冒泡兼容 if (event.stopPropagation) { event.stopPropagation(); } else {//兼容ie event.cancelBubble = true; } }, getRelatedTarget: function (event) {//mouseout和mouseover事件时,获取相关元素 if (event.relatedTarget) { return event.relatedTarget; } else if (event.toElement) { return event.toElement; } else if (event.fromElement) { return event.fromElement; } else { return null; } }, getButton: function (event) {//mousedown和mouseup事件,返回值 0表示鼠标左键,1表示中间的鼠标按钮(鼠标滚轮按钮),2表示次鼠标右键 if (document.implementation.hasFeature("MouseEvents", "2.0")) { return event.button; } else { switch (event.button) { case 0: case 1: case 3: case 5: case 7: return 0; case 2: case 6: return 2; case 4: return 1; } } }, getWheelDelta: function(event) {//兼容鼠标滚轮事件 if (event.wheelDelta) { //在 Opera 9.5 之前的版本中,wheelDelta 值的正负号是颠倒的。如果你打算支持早期的 Opera 版本,就需要使用浏览器检测技术来确定实际的值 return (client.engine.opera && client.engine.opera < 9.5 ? -event.wheelDelta : event.wheelDelta); } else { return -event.detail * 40; } }, getCharCode: function(event){ //兼容获取当前键盘事件的ASCII编码 if (typeof event.charCode == "number"){ return event.charCode; } else { return event.keyCode; } }, getClipboardText: function(event){//兼容获取剪贴板内容 var clipboardData = (event.clipboardData || window.clipboardData); return clipboardData.getData("text"); }, setClipboardText: function(event, value){//兼容设置剪贴板内容 if (event.clipboardData){ return event.clipboardData.setData("text/plain", value); } else if (window.clipboardData){//兼容ie return window.clipboardData.setData("text", value); } }, };