检查是否可以添加事件侦听器而不添加

Check if adding an event listener is possible without adding one

本文关键字:添加 侦听器 事件 检查 是否      更新时间:2023-12-12

我想添加滚动事件侦听器或触摸启动事件侦听器。最初,我使用触摸事件来停用滚动事件监听器,如下代码所示:

window.addEventListener('scroll', scrollStart, false);
window.addEventListener('touchstart', touchStart, false);
function scrollMenu() {
    // do something
}
function touchStart(e) {
    window.removeEventListener('scroll', scrollStart);
    // do something
}

但我意识到,在某些情况下,页面一加载就会触发滚动事件。因此,我不能使用上述方法。是否有其他方法可以在不添加事件的情况下检查浏览器是否支持触摸事件侦听器?

Modernizr能解决您的问题吗?请参阅此处的示例,了解检测触摸事件的各种方法以及每个触摸事件的浏览器兼容性:

http://modernizr.github.com/Modernizr/touch.html

应该能够检查window:中是否存在ontouchstart属性

if ("ontouchstart" in window) {
    window.addEventListener('touchstart', touchStart, false);
} else {
    window.addEventListener('scroll', scrollStart, false);
}

不过,我无法确认这件事的浏览性。