【发布时间】:2018-02-07 09:50:15
【问题描述】:
例如:document.body.addEventListener('wheel', foo, {passive: true});
如果屏幕尺寸大于500px,则应动态添加/删除它
【问题讨论】:
-
所以在调整大小时添加/删除它......
标签: javascript html css dom ecmascript-6
例如:document.body.addEventListener('wheel', foo, {passive: true});
如果屏幕尺寸大于500px,则应动态添加/删除它
【问题讨论】:
标签: javascript html css dom ecmascript-6
正如@Rounin 所说,window.matchMedia 相当于 CSS @media 查询。但最酷的部分不仅在于您可以通过.matches 进行检查 - 很棒的是,您可以添加一个事件侦听器,该事件侦听器会在状态更改时触发。
您希望在屏幕宽度转换到高于或低于 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 个选项:
> 500 时添加侦听器:最简单的解决方案,但如果用户调整窗口大小则不会调整。添加一个监听器来调整窗口大小,每次宽度改变时,根据宽度添加或删除'wheel'事件监听器。
始终向'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()
【讨论】: