Detect dynamic media queries with JavaScript?

前端 未结 4 806
误落风尘
误落风尘 2021-01-13 06:16

I\'ve been searching for a lightweight, flexible, cross-browser solution for accessing CSS Media Queries in JavaScript, without the CSS breakpoints being repeated in the Jav

4条回答
  •  春和景丽
    2021-01-13 07:13

    See this post from expert David Walsh Device State Detection with CSS Media Queries and JavaScript:

    CSS

    .state-indicator {
        position: absolute;
        top: -999em;
        left: -999em;
    }
    .state-indicator:before { content: 'desktop'; }
    
    /* small desktop */
    @media all and (max-width: 1200px) {
        .state-indicator:before { content: 'small-desktop'; }
    }
    
    /* tablet */
    @media all and (max-width: 1024px) {
        .state-indicator:before { content: 'tablet'; }
    }
    
    /* mobile phone */
    @media all and (max-width: 768px) {
        .state-indicator:before { content: 'mobile'; }
    }
    

    JS

    var state = window.getComputedStyle(
        document.querySelector('.state-indicator'), ':before'
    ).getPropertyValue('content')
    

    Also, this is a clever solution from the javascript guru Nicholas C. Zakas:

      // Test a media query.
      // Example: if (isMedia("screen and (max-width:800px)"){}
      // Copyright 2011 Nicholas C. Zakas. All rights reserved.
      // Licensed under BSD License.
      var isMedia = (function () {
    
        var div;
    
        return function (query) {
    
          //if the 
    doesn't exist, create it and make sure it's hidden if (!div) { div = document.createElement("div"); div.id = "ncz1"; div.style.cssText = "position:absolute;top:-1000px"; document.body.insertBefore(div, document.body.firstChild); } div.innerHTML = "_"; div.removeChild(div.firstChild); return div.offsetWidth == 1; }; })();

提交回复
热议问题