如何根据屏幕大小将事件侦听器附加到 DOM

hey*_*ush 6 html javascript css dom ecmascript-6

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

Ste*_*n P 6

正如 @Rounin 所说,window.matchMedia相当于 CSS @media 查询。但最酷的部分不仅仅是您可以检查.matches- 最棒的是您可以添加一个事件侦听器,当状态更改时该事件侦听器会被触发。

您希望当屏幕宽度过渡到 500 像素以上或以下时发生一些事情 - 您希望在屏幕 > 500 像素时添加鼠标滚轮侦听器,并在屏幕 < 500 像素时将其删除

您还必须.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
    }
});
Run Code Online (Sandbox Code Playgroud)


Dan*_*sky 2

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()
Run Code Online (Sandbox Code Playgroud)