如何将事件侦听器附加到DOM,具体取决于屏幕大小

时间:2017-08-29 20:07:42

标签: javascript html5 css3 dom ecmascript-6

例如:document.body.addEventListener('wheel', foo, {passive: true}); 如果屏幕尺寸高于500px

,则应动态添加/删除此内容

4 个答案:

答案 0 :(得分:4)

正如@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
    }
});

答案 1 :(得分:2)

  

仅在屏幕上如何将事件侦听器附加到DOM [...]   大小高于500px

window.matchMedia是CSS @media查询的javascript等价物。

例如,以下代码验证屏幕宽度是否高于500px

var widerScreenWidth = window.matchMedia("(min-width: 501px)");

if (widerScreenWidth.matches) {

    // [... YOUR CODE HERE...]

}

答案 2 :(得分:2)

你有3个选择:

  1. 检查加载时的窗口大小,如果> 500:最简单的解决方案,则添加监听器,但如果用户调整窗口大小,则不会调整。
  2. 为窗口调整大小添加一个监听器,每次宽度更改时,根据宽度添加或删除'wheel'事件监听器。

  3. 总是向'wheel'添加一个事件监听器,但在事件回调中,每次回调运行时检查宽度,然后再执行逻辑

答案 3 :(得分:1)

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()