如何将事件侦听器连接到DOM,具体取决于屏幕尺寸



for eg: document.body.addEventListener('wheel', foo, {passive: true});如果屏幕大小在500px

上方,则应动态添加/删除。

正如@Rounin所说, window.matchMedia等效于css @media查询。但是最酷的部分不仅是您可以使用.matches检查 - 很棒的是,您可以添加当状态更改时发射的事件列表

当屏幕宽度过渡到上方或以下500px以下时,您希望发生某些事情 - 您想在屏幕> 500px时添加鼠标轮式侦听器并在屏幕为< 500px

时将其删除。

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

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 [...] 大小高于500px

window.matchMedia是CSS @media查询的JavaScript等效。

例如,以下代码验证屏幕宽度在500px上方。

var widerScreenWidth = window.matchMedia("(min-width: 501px)");
if (widerScreenWidth.matches) {
    // [... YOUR CODE HERE...]
}

您有3个选项:

  1. 检查加载上的窗口大小,如果> 500:最简单的解决方案,则添加了侦听器,但如果用户调整窗口大小,则不会调整。
  2. 在窗口大小中添加侦听器,每当宽度更改时,添加或删除'wheel'事件侦听器,取决于宽度。

  3. 始终将事件侦听器添加到'wheel',但是在事件回调中,每次回调在执行逻辑之前运行时检查宽度

function getScreenWidth() {
  var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0]
  return w.innerWidth || e.clientWidth || g.clientWidth
}
function wheelListener() {
  console.log(getScreenWidth())
}
window.onresize = function() {
  if (getScreenWidth() > 500) {
    document.body.addEventListener('wheel', wheelListener, {passive: true})
  } else {
    document.body.removeEventListener('wheel', wheelListener)
  }
}
// to apply when the window loaded
window.onresize()

最新更新