事件的绑定-addEventListener
利用函数addEventListener(‘事件’,function (){})可以是同个元素执行多个程序
big.addEventListener('click',function(){ console.log("大"); },true) //在函数后面加true可以使这个div在捕捉阶段就被捕捉输出 middle.addEventListener('click',function(){ console.log("中"); }) small.addEventListener('click',function(){ console.log("小"); },true)
系统提供了一个方法,addEventListener() - 可以将同类型的事件绑定多次
语法:标签.addEventListener(事件类型,函数)
参数3是可选项,是布尔值,默认false - 是否在捕获阶段执行
box.addEventListener('click',function(){
console.log("点击了div");
})
这种绑定方式在低版本ie中不兼容
ie中换写法 - 标签.attachEvent(on+事件类型,函数)
box.attachEvent('onclick',function(){ console.log("点击了div"); })
封装万能的绑定事件的函数
function bindEvent(ele,type,handler){ if(ele.addEventListener){ ele.addEventListener(type,handler) }else if(ele.attachEvent){ ele.attachEvent('on'+type,handler) }else{ ele['on' + type] = handler } } function fn(){ console.log("点击了div"); } bindEvent(box,'click',fn) function fun(){ console.log("进来了"); } bindEvent(box,'mouseover',fun)