ruilove

js原生添加事件的方式

2017-06-11 18:38  angry_rookie  阅读(2232)  评论(0编辑  收藏  举报

js原生添加事件的方式:

1. 直接在html标签上添加

<div onclick="alert(\'div\')">div</div>

2. domon...方法添加

document.getElementById(\'div\').onclick = function () {alert(\'div\')};

3. addEventListenerattachEvent添加

document.getElementById(\'div\').addEventListener(\'click\', function () {alert(\'div\')}, false);

 

 

原生js事件绑定和事件移除

/**  

 * @description 事件绑定,兼容各浏览器  

 * @param target 事件触发对象   

 * @param type   事件  

 * @param func   事件处理函数  

 */  

function addEvents(target, type, func) {  

    if (target.addEventListener)    //ie ie9  

        target.addEventListener(type, func, false);  

// addEventListener当然就是注册事件,她有三个参数,分别为:"事件名称", "事件回调", "捕获/冒泡"。最后一个参数是布尔型,true代表捕获事件,false代表冒泡事件。

    else if (target.attachEvent)   //ie6ie8  

        target.attachEvent("on" + type, func);  

    else target["on" + type] = func;   //ie5  

};  

 

/**  

 * @description 事件移除,兼容各浏览器  

 * @param target 事件触发对象  

 * @param type   事件  

 * @param func   事件处理函数  

 */  

function removeEvents(target, type, func){  

    if (target.removeEventListener)  

        target.removeEventListener(type, func, false);  

    else if (target.detachEvent)  

        target.detachEvent("on" + type, func);  

    else target["on" + type] = null;  

};  

/**btn.removeEventListener("事件名称", "事件回调", "捕获/冒泡");这和绑定事件的参数一样,详细说明下:        

·  事件名称,就是说解除哪个事件呗。

·  事件回调,是一个函数,这个函数必须和注册事件的函数是同一个。

·  事件类型,布尔值,这个必须和注册事件时的类型一致。

*/

分类:

技术点:

相关文章:

  • 2021-11-05
  • 2021-10-03
  • 2022-01-06
  • 2021-12-19
  • 2022-01-13
  • 2022-01-15
  • 2021-07-14
  • 2021-11-01
猜你喜欢
  • 2021-12-19
  • 2021-10-01
  • 2021-11-28
  • 2021-10-19
  • 2021-05-19
  • 2022-01-10
  • 2021-05-20
相关资源
相似解决方案