码迷,mamicode.com
首页 > Web开发 > 详细

封装addEventListener,removeEventListener指定元素添加事件及兼容问题js

时间:2020-05-16 00:23:57      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:call   UNC   use   false   cap   type   document   resize   fun   

HTML DOM addEventListener() 方法 和 HTML DOM removeEventListener()某些浏览器还是存在兼容问题,以下封装了这两个方法:
// Events
// on(node, eventName, handler, [capture]): capture is silently ignored in ie8
export const addEventListener = (function() {
  if (typeof document === ‘undefined‘) {
    return () => {};
  }

  if (document.addEventListener) {
    return (node, eventName, handler, capture) =>
      node.addEventListener(eventName, handler, capture || false);
  }

  if (document.attachEvent) {
    return (node, eventName, handler) =>
      node.attachEvent(`on${  eventName}`, (e) => {
        e = e || window.event;
        e.target = e.target || e.srcElement;
        e.currentTarget = node;
        handler.call(node, e);
      });
  }
})();
export const on = addEventListener;

// off(node, eventName, handler, [capture]): capture is silently ignored in ie8
export const removeEventListener = (function() {
  if (typeof document === ‘undefined‘) {
    return () => {};
  }

  if (document.addEventListener) {
    return (node, eventName, handler, capture) =>
      node.removeEventListener(eventName, handler, capture || false);
  }

  if (document.attachEvent) {
    return (node, eventName, handler) =>
      node.detachEvent(`on${  eventName}`, handler);
  }
})();
export const off = removeEventListener;

调用方法:

useEffect(() => {
    addEventListener(window, ‘resize‘, demo());

    return () => {
      removeEventListener(window, ‘resize‘, demo());
    };
  }, []);

  

封装addEventListener,removeEventListener指定元素添加事件及兼容问题js

标签:call   UNC   use   false   cap   type   document   resize   fun   

原文地址:https://www.cnblogs.com/a-cat/p/12897754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!