封装addEventListener,removeEventListener指定元素添加事件及兼容问题js
2021-03-06 06:29
标签:call UNC use false cap type document resize fun 调用方法: 封装addEventListener,removeEventListener指定元素添加事件及兼容问题js 标签:call UNC use false cap type document resize fun 原文地址:https://www.cnblogs.com/a-cat/p/12897754.htmlHTML 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
文章链接:http://soscw.com/index.php/essay/60745.html