JavaScript事件绑定、事件解绑 | 您所在的位置:网站首页 › 5e能解绑 › JavaScript事件绑定、事件解绑 |
绑定事件 addEventListener() 与 attachEvent(),这两个函数,都可以做事件绑定。 绑定事件 addEventListener 与 attachEvent 的区别 相同点:都可以绑定事件 不同点: 方法名不一样 参数个数不一样 addEventListener(element,function,false); attachEvent(element,function); addEventListener 谷歌,火狐,IE11支持,IE8不支持 attachEvent 谷歌,火狐,IE11不支持,IE8支持 this不同,addEventListener中的this是当前绑定事件的对象 attachEvent中的this是window addEventListener 中事件的类型(事件的名字)没有on attachEvent 中事件的类型(事件的名字)有on javascript中路由跳转的原理 京东 登录 注册 用户中心 // 绑定事件 addEventListener() var main = document.querySelector('#main'); var container = document.querySelector('#container'); console.log(main,container) window.addEventListener('hashchange',function(){ console.log(location.hash); //多路分支 switch(location.hash){ case "#/login": container.innerHTML='我是登录页' break; case "#/register": container.innerHTML='我是注册页' break; case "#/user": container.innerHTML='我是用户中心页' break; } })预览: 重要事情说三遍:attachEvent是IE浏览器独有的!!!attachEvent是IE浏览器独有的!!!attachEvent是IE浏览器独有的!!! 为对象注册多个事件 var box=document.getElementById('box') console.log(box); box.attachEvent('onmouseover',function(){ console.log('移入'); }) box.attachEvent('onmouseout',function(){ console.log('移出'); })
在IE11版本浏览器打开运行程序,IE11不支持attachEvent; 解决办法就是: 通过在html的head标签中加入 让IE的默认版本为IE10,在IE控制台也可以直接修改IE的版本,便于调试。预览: 事件解绑 removeEventListener() 事件解绑,就是移除事件。“干掉” detachEvent() 点击 干掉第一个按钮的事件//抓取元素 var btn1=document.querySelector('#btn1') var btn2=document.querySelector('#btn2') console.log(btn1,btn2); var open=true; function change(){ if(open==true){ document.body.style.backgroundColor='lightblue' open=false; }else{ document.body.style.backgroundColor='pink'; open=true } } //给第一个按钮 绑定事件 btn1.addEventListener('click',change) //给第二个按钮 解绑事件 btn2.addEventListener('click',function(){ //哪个对象 进行解绑,解绑什么事件, btn1.removeEventListener('click',change) }) 预览: 点击按钮移除 DIV 的事件句柄。 点我#box{ background-color:coral; border:1px solid; padding:50px; color:#fff; } document.querySelector('#box').addEventListener('mousemove',myFunction) function myFunction(){ document.querySelector('#demo').innerHTML=Math.random() } function removeHandler(){ //事件解绑 document.querySelector('#box').removeEventListener('mousemove',myFunction) } 预览:
|
CopyRight 2018-2019 实验室设备网 版权所有 |