如何在 vanilla js 中插入媒体查询?

如何仅在 SP 视图上运行此 javascript。


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');

    const mediaQuery = window.matchMedia('(min-width: 768px)')

    document.body.classList.toggle('overflow'); // THIS CODE

});


鸿蒙传说
浏览 89回答 2
2回答

胡子哥哥

查明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    }});

肥皂起泡泡

聆听变化// Create a condition that targets viewports at least 768px wideconst 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 listenermediaQuery.addListener(handleTabletChange)// Initial checkhandleTabletChange(mediaQuery)更多例子// media query event handlerif(matchMedia) {    const mq = window.matchMedia("(min-width: 500px)");    mq.addListener(WidthChange);    WidthChange(mq);}// media query changefunction WidthChange(mq) {    if (mq.matches) {        // window width is at least 500px    } else {        // window width is less than 500px    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript