Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. 通过 on 来绑定事件
  2. on 绑定问题:只能给元素绑定一次相同的事件,第二次会把第一次覆盖
  3. div.onclick = function(){
  4. this.style.display="inline-block";
  5. this.style.backgroundColor="red";
  6. }
  7. div.onclick = function(){
  8. this.style.display="inline-block";
  9. this.style.backgroundColor="yellow";
  10. }
  11. 通过on绑定 取消
  12. div。onclick = null
  13.  
  14.  
  15. 通过方法 addEvenListener()来添加事件
  16. 参数1:添加的事件名称
  17. 参数2:事件触发时,执行的函数
  18. 参数3:是一个布尔字false表示该事件以冒泡的方式传递 true是捕获的方式来传递
  19. 第三个参数通常不用设置,默认false
  20. 该方法和no的相同点:谁调用,添加给谁。都是给元素添加事件
  21. 不同点: 1.该方法可以通过第三个参数来控制事件传递的传递方式
  22. 2.可以给元素绑定多次相同事件,且相互之间不会覆盖
  23.  
  24. div.addEventListener("click",function(){
  25. this.innerHTML = "啊~我被点了"
  26. this.style.background="yellow"
  27. })
  28. var i=0
  29. div.addEventListener("mousedown",myFun,true);
  30.  
  31. function myFun(){
  32. this.innerHTML="我又被点了";
  33. i++
  34. }
  35.  
  36. div.addEventListener("mousedown",myFun_tow,true);
  37. function myFun_tow(){
  38. this.style.background="yellow";
  39. i++
  40. }
  41. div.addEventListener("mousedown",myFun_three,true);
  42. function myFun_three(){
  43. this.style.width=200+"px";
  44. i++
  45. }
  46. div.addEventListener("mouseup",function(){
  47. this.innerHTML="我是一个野生的div";
  48. this.style.background="white";
  49. this.style.width=100+"px";
  50.  
  51. });
  52.  
  53.  
  54.  
  55. div.ondblclick = function(){
  56. this.removeEventListener("mousedown",myFun_three,true)
  57. this.removeEventListener("mousedown",myFun_tow,true)
  58.  
  59. }
  60. 取消绑定事件
  61. 参数1:要删除的事件类型
  62. 参数2:要删除的函数名,不要函数后面的小括号,和添加时一致(这个函数不能是匿名函数,否则无法删除)
  63. 参数3:可选 但添加时设置了,这里也必须保持一致,否则无法删除
  64. 要删除一个事件,需要指定类型,指定函数名,指定事件传递的顺序,三者一致可删除
  65. div.removeEventListener("click",myFun,true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement