标签: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