类型
addEventListener()
. 现在您正在传递函数引用,但需要一个字符串。试试这个:
const buttonMenu = document.querySelector('.js-desktop-menu');
const getEventType = () => 'ontouchend' in document.documentElement ? 'touchend' : 'click';
buttonMenu.addEventListener(getEventType(), e => {
if (window.innerWidth >= 992) {
// Something
} else {
// Something else
}
});
这里要注意两件事。首先,我使用三元表达式和箭头函数使函数变得更加简洁,但逻辑是相同的。
其次,你使用
querySelector()
这意味着只有一个元素将存在于具有所提供选择器的DOM中,但是您给它一个类选择器。如果您添加了多个
.js-desktop-menu
未来的元素。