Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 通过 on 来绑定事件
- on 绑定问题:只能给元素绑定一次相同的事件,第二次会把第一次覆盖
- div.onclick = function(){
- this.style.display="inline-block";
- this.style.backgroundColor="red";
- }
- div.onclick = function(){
- this.style.display="inline-block";
- this.style.backgroundColor="yellow";
- }
- 通过on绑定 取消
- div。onclick = null
- 通过方法 addEvenListener()来添加事件
- 参数1:添加的事件名称
- 参数2:事件触发时,执行的函数
- 参数3:是一个布尔字false表示该事件以冒泡的方式传递 true是捕获的方式来传递
- 第三个参数通常不用设置,默认false
- 该方法和no的相同点:谁调用,添加给谁。都是给元素添加事件
- 不同点: 1.该方法可以通过第三个参数来控制事件传递的传递方式
- 2.可以给元素绑定多次相同事件,且相互之间不会覆盖
- div.addEventListener("click",function(){
- this.innerHTML = "啊~我被点了"
- this.style.background="yellow"
- })
- var i=0
- div.addEventListener("mousedown",myFun,true);
- function myFun(){
- this.innerHTML="我又被点了";
- i++
- }
- div.addEventListener("mousedown",myFun_tow,true);
- function myFun_tow(){
- this.style.background="yellow";
- i++
- }
- div.addEventListener("mousedown",myFun_three,true);
- function myFun_three(){
- this.style.width=200+"px";
- i++
- }
- div.addEventListener("mouseup",function(){
- this.innerHTML="我是一个野生的div";
- this.style.background="white";
- this.style.width=100+"px";
- });
- div.ondblclick = function(){
- this.removeEventListener("mousedown",myFun_three,true)
- this.removeEventListener("mousedown",myFun_tow,true)
- }
- 取消绑定事件
- 参数1:要删除的事件类型
- 参数2:要删除的函数名,不要函数后面的小括号,和添加时一致(这个函数不能是匿名函数,否则无法删除)
- 参数3:可选 但添加时设置了,这里也必须保持一致,否则无法删除
- 要删除一个事件,需要指定类型,指定函数名,指定事件传递的顺序,三者一致可删除
- div.removeEventListener("click",myFun,true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement