Happy New Year!

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

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());
    };
  }, []);

  

posted @ 2020-05-15 22:57  一只看夕阳的猫  阅读(524)  评论(0编辑  收藏  举报
返回顶部小火箭
世界很公平,想要最好,就一定得付出!
x
博客主页