1
我有这个JavaScript代码,使我的网站的顶部导航缩小。见下文:在Javascript事件监听器中包含CSS媒体查询
<script>
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 300,
header = document.querySelector("header");
if (distanceY > shrinkOn) {
classie.add(header,"smaller");
} else {
if (classie.has(header,"smaller")) {
classie.remove(header,"smaller");
}
}
});
}
window.onload = init();
</script>
的代码添加类“较小”到当窗口被向下滚动规定的距离,并降低它来滚动备份时的标头部分。 但是,我希望仅当屏幕大于768像素(即最小宽度:768像素)时才能添加和删除该类。在较小的屏幕尺寸上,我不希望添加和删除类工作。
我看到了一个使用代码的例子,但我不知道如何将它添加到我上面的代码中。
// media query event handler
if (matchMedia) {
const mq = window.matchMedia("(min-width: 500px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
}
任何关于如何结合这一点的帮助将不胜感激。
您可以覆盖风格,这是一个'MAX-width'媒体查询中添加类的,因此不需要额外的JavaScript。或者,如果没有重写,只能在大型媒体查询中应用这些类风格,即'min-width:768px' –
谢谢James。仔细一看,我意识到这可以通过媒体查询覆盖像你说的。 – atsngr