javascript 中的多个媒体查询

Multiple media queries in javascript

我正在尝试使用 Javascript 检查屏幕尺寸。 我的元素将根据屏幕大小进行不同的动画处理。

我想我离结果不太远,但还没有真正完全理解它。

当我加载页面时,无论 window.

的大小如何,我都会出现两次 console.log

手动缩小window,拖动鼠标,有: - 2 console.log('MD') 当 MD 的大小合适时 - 1 console.log('SM') 当 SM 尺寸合适时

手动放大window,拖动鼠标,有: - 1 console.log('MD') 当 MD 的大小合适时 - 1 console.log('SM') 当 LG 尺寸合适时 - 1 console.log('LG') 当 LG 尺寸合适时

但是通过浏览器图标调整window的大小,我的console.log就如我所愿

能不能多解释一下?

我希望我已经说清楚了。

let mqls = [

    window.matchMedia('screen and (min-width: 768px) and (max-width: 991px'),
    window.matchMedia('screen and (min-width: 992px)')
    
  ];


  function test(mql){

    if( mqls[0].matches ){

        console.log('MD')
    }

    else if( mqls[1].matches ){

        console.log('LG')
    }
    else if( !mqls[0].matches && !mqls[1].matches ){

        console.log('SM')
    }
  }

   for ( let i =0; i < mqls.length; i++ ){

     test(mqls[i]);
     mqls[i].addListener(test);
   }

function checkScreen(){


  const checkMobile = window.matchMedia('screen and (max-width: 575px)');
  const checkTablet = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');
  const checkDesktop = window.matchMedia('screen and (min-width: 992px)');

  checkMobile.addListener(function(e){

    if(e.matches) {

        console.log('MOBILE');
    }
  });

  checkTablet.addListener(function(e){

    if(e.matches) {

        console.log('TABLET');
    }
  });

  checkDesktop.addListener(function(e){

    if(e.matches) {

        console.log('DESKTOP');
    }
  });

  
  
}
checkScreen()

我想通了,但也许有更好的解决方案?

已编辑

使用上面的解决方案,当我的页面加载或刷新时我的函数没有启动,所以我必须这样做

mobile();
function mobile(){

    const mql = window.matchMedia('screen and (max-width: 575px)');

    checkMedia(mql);
    mql.addListener(checkMedia);

    function checkMedia(mql){

        if(mql.matches){

            console.log('Mobile');
        }
    }
}

tablet();
function tablet(){

    const mql = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');

    checkMedia(mql);
    mql.addListener(checkMedia);

    function checkMedia(mql){

        if(mql.matches){

            console.log('tablet');
        }
    }
}


desktop();
function desktop(){

    const mql = window.matchMedia('screen and (min-width: 992px)');

    checkMedia(mql);
    mql.addListener(checkMedia);

    function checkMedia(mql){

        if(mql.matches){

            console.log('desktop');
        }
    }
}

如果我将媒体查询放在一个数组中,并在每次刷新时使用循环,控制台中的输出与数组中的项目一样多

可能有些地方我不明白。