JS基础学习四:绑定事件

添加事件 
IE: attachEvent 
Other: addEventListener 

Java代码  收藏代码
  1. var button = document.getElementById("buttonId");  
  2. if(button.addEventListener){  
  3.     button.addEventListener("click",eventFunction,false);  
  4. }else if(button.attachEvent){  
  5.     button.attachEvent("onclick",eventFunction);  
  6. }  



删除事件 
IE: detachEvent 
Other: removeEventListener 

事件冒泡机制 
IE: 事件从它发生的地方被触发,然后向DOM结构的上层冒泡 
Other: 事件先向下沉入到目标元素,再向上冒泡 
     addEventListener( , ,[true|false]) 

  • true: 向下沉入时截获事件
  • false: 向上冒泡时截获事件



停止事件冒泡: 
IE: window.event.cancelBubble=false; 
Other: e.stopPropagation(); 

实验的例子: 

Java代码  收藏代码
  1. function bindEvent() {  
  2.     var button = document.getElementById("buttonId");  
  3.     if (button.addEventListener) {  
  4.         alert("Other browser");  
  5.         //button.addEventListener("click",showEvent,false);  
  6.         //button.addEventListener("click",showEvent2,false);  
  7.         button.addEventListener("click", showEvent, true);  
  8.         button.addEventListener("click", showEvent2, true);  
  9.     } else if (button.attachEvent) {  
  10.         alert("IE browser");  
  11.         button.attachEvent("onclick", showEvent);  
  12.         button.attachEvent("onclick", showEvent2);  
  13.     }  
  14. }  
  15.   
  16. function removeEvent() {  
  17.     var button = document.getElementById("buttonId");  
  18.     if (button.removeEventListener) {  
  19.         alert("Other browser");  
  20.         //button.removeEventListener("click",showEvent,false);  
  21.         button.removeEventListener("click", showEvent, true);  
  22.     } else if (button.detachEvent) {  
  23.         alert("IE browser");  
  24.         button.detachEvent("onclick", showEvent);  
  25.     }  
  26. }  
  27.   
  28. function showEvent(e) {  
  29.     if (window.event != undefined) {  
  30.         window.event.cancelBubble = true;  
  31.     } else if (e.stopPropagation) {  
  32.         e.stopPropagation();  
  33.     }  
  34.     alert("Event here!");  
  35. }  
  36.   
  37. function showEvent2() {  
  38.     alert("Other event here!");  
  39. }  
  40.   
  41. function divEvent() {  
  42.     alert("Div Event");  
  43. }  



Html代码  收藏代码
  1. <div onclick="divEvent()">  
  2.     <input type="button" id="buttonId" value="showEvent"/>  
  3. </div>  



键盘事件 

Java代码  收藏代码
  1. window.onload=function(){  
  2.      //绑定键盘事件  
  3.      document.onkeydown=showkey;  
  4. }  
  5.   
  6. function showkey(e){  
  7.      var key;  
  8.      if(window.event)  
  9.           key= window.event.keyCode;  
  10.      else  
  11.           key= e.keyCode;  
  12.   
  13.      alert(String.fromCharCode(key));  
  14. }  



鼠标事件 
获取mouse的位置 
IE: clientX,clientY 
Other: pageX, pageY 

Java代码  收藏代码
    1. document.onmouseover= showPosition;  
原文地址:https://www.cnblogs.com/zjx2011/p/3214801.html