封装addEventListener,removeEventListener指定元素添加事件及兼容问题js
Posted 一只看夕阳的猫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装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()); }; }, []);
以上是关于封装addEventListener,removeEventListener指定元素添加事件及兼容问题js的主要内容,如果未能解决你的问题,请参考以下文章