2 回答
TA贡献1825条经验 获得超6个赞
查明matchMedia()屏幕宽度是否小于或大于 768 像素。如果满足条件则执行代码
const navTrigger = document.querySelector('.nav__trigger');
const nav = document.querySelector('nav');
navTrigger.addEventListener('click', event => {
event.preventDefault();
navTrigger.classList.toggle('nav__trigger--active');
nav.classList.toggle('nav--open');
if (window.matchMedia("(min-width: 768px)").matches) {
document.body.classList.toggle('overflow'); // THIS CODE
}
});
TA贡献1829条经验 获得超6个赞
聆听变化
// Create a condition that targets viewports at least 768px wide
const mediaQuery = window.matchMedia('(min-width: 768px)')
function handleTabletChange(e) {
// Check if the media query is true
if (e.matches) {
// Then log the following message to the console
console.log('Media Query Matched!')
}
}
// Register event listener
mediaQuery.addListener(handleTabletChange)
// Initial check
handleTabletChange(mediaQuery)
更多例子
// 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
}
}
添加回答
举报