【问题标题】:Multiple media queries in javascriptjavascript中的多个媒体查询
【发布时间】:2019-10-30 11:53:57
【问题描述】:

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

我认为我离结果并没有太远,但没有真正完全理解它。

当我加载页面时,无论窗口大小如何,都会有一个 console.log 出现两次。

通过手动缩小窗口,通过鼠标拖动,有: - 2 console.log('MD') 当 MD 大小正常时 - 1 console.log('SM') 当 SM 大小正常时

通过手动放大窗口,通过拖动鼠标,有: - 1 console.log('MD') 当 MD 大小正常时 - 1 console.log('SM') 当 LG 的大小正常时 - 当 LG 的大小正常时 1 个 console.log('LG')

但是通过浏览器图标调整窗口大小,我的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);
   }

【问题讨论】:

  • 这种行为究竟是什么让您感到困惑或出乎意料?
  • 了解开发工具的输出
  • 变量mqls是一个有两个元素的数组,你用for loop来检查屏幕大小,所以控制台输出会根据mqls数组长度加倍。

标签: javascript html css media-queries


【解决方案1】:

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

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

可能有一些我不明白的地方。

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2011-10-15
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多