JS基础学习四:绑定事件

时间:2023-03-09 23:19:24
JS基础学习四:绑定事件

添加事件 
IE: attachEvent 
Other: addEventListener

  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();

实验的例子:

  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. function removeEvent() {
  16. var button = document.getElementById("buttonId");
  17. if (button.removeEventListener) {
  18. alert("Other browser");
  19. //button.removeEventListener("click",showEvent,false);
  20. button.removeEventListener("click", showEvent, true);
  21. } else if (button.detachEvent) {
  22. alert("IE browser");
  23. button.detachEvent("onclick", showEvent);
  24. }
  25. }
  26. function showEvent(e) {
  27. if (window.event != undefined) {
  28. window.event.cancelBubble = true;
  29. } else if (e.stopPropagation) {
  30. e.stopPropagation();
  31. }
  32. alert("Event here!");
  33. }
  34. function showEvent2() {
  35. alert("Other event here!");
  36. }
  37. function divEvent() {
  38. alert("Div Event");
  39. }
  1. <div onclick="divEvent()">
  2. <input type="button" id="buttonId" value="showEvent"/>
  3. </div>

键盘事件

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

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

    1. document.onmouseover= showPosition;