兼容浏览器的点击事件
IE和其他浏览器在一些方法上存在差异:
1.获取事件,IE通过window.event
2.获取触发事件的节点 W3C标准: e.target
IE: e.srcElement;
3.阻止冒泡 W3C标准:stopPropagation()
IE中: cancelBubble = true;
4.阻止默认操作 W3C标准: preventDefault()
IE中: returnValue = false;
5.事件监听 W3C标准: document.addEventListener('click', func, false)
IE中: document.attachEvent('click', func)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button id="clickme">Click me: 9</button> <script> function myHandler(e) { var src, parts; // 获取事件和触发事件的节点 e = e || window.event; target = e.target || e.srcElement; // 实际工作 parts = target.innerHTML.split(": "); parts[1] = parseInt(parts[1], 10)+1; target.innerHTML = parts[0] + ": " + parts[1]; // 阻止冒泡 if (typeof e.stopPropagation === "function") { e.stopPropagation(); } if (typeof e.cancelBubble !== "undefined") { e.cancelBubble = true; } //阻止默认操作 if (typeof e.preventDefault === "function") { e.preventDefault(); } if (typeof e.returnValue !== "undefined") { e.returnValue = false; } } var clickMe = document.getElementById('clickme'); if (document.addEventListener) { // 一般浏览器 clickMe.addEventListener('click', myHandler, false); } else if (document.attachEvent) { // IE clickMe.attach('click',myHandler); } else { // last resort clickMe.onclick = myHandler; } </script> </body> </html>
运行效果(每次值加1)
.......