本文介绍了如何将事件侦听器附加到DOM,具体取决于屏幕大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如: document.body.addEventListener('wheel',foo,{passive:true});
这应该动态添加/删除屏幕尺寸高于 500px

推荐答案

正如@Rounin所说, window.matchMedia 相当于CSS @media查询。但最酷的部分不仅仅是你可以用 .matches 来检查 - 很棒的是你可以添加一个事件监听器当状态改变时触发。

As @Rounin says, window.matchMedia is the equivalent of CSS @media queries. But the coolest part is not just that you can check with .matches -- the awesome thing is that you can add an event-listener that gets fired when the state changes.

当屏幕宽度转换到500px以上或者低于500px时你想要发生什么 - 你想在屏幕上添加一个鼠标滚轮监听器> 500px并在屏幕显示时将其删除

You want something to happen when the screen width transition to above or below 500px -- you want to add a mouse wheel listener when the screen is >500px and remove it when the screen is <500px

您还必须先检查 .matches 决定是否在首次加载页面时添加监听器,如@Rounin所示,但是可以根据匹配的媒体查询自动添加和删除监听器。

You will also have to check for .matches initially to decide whether to add the listener or not when your page first loads, as @Rounin shows, but then the listener can be added and removed automatically based on matching the media query.

let widthMatch = window.matchMedia("(min-width: 500px)");
// mm in the function arg is the matchMedia object, passed back into the function
widthMatch.addEventListener('change', function(mm) {
    if (mm.matches) {
        // it matches the media query: that is, min-width is >= 500px
        document.body.addEventListener( etc. );
    }
    else {
        // it no longer matches the media query
        // remove the event listener
    }
});

这篇关于如何将事件侦听器附加到DOM,具体取决于屏幕大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 11:08