简体   繁体   中英

how to use javascript to detect whether a web page is responsive on mobile

I need to use javascript to detect whether a page is responsive. On a galaxy note 3, here are the values for a non-responsive and a responsive pages:

non-responsive: 
window.innerWidth:980 
clientWidth:980 
screen.width:640 

responsive: 
window.innerWidth:640 
clientWidth:640 
screen.width:640 

So is it correct to say that if clientWidth == screen.width then it is responsive, else it is non-responsive?

As you know, there's an important feature used in responsive design call media query, with which browser can switch alternative CSS rules for different screen resolutions to make page "responsive".

You can enum CSS rules in Javascript using document.styleSheets . And CSS like

@media all and (max-width:1023px) {
    /* some styles */
}

will add some instances of CSSMediaRule in cssRules collection. Here's my detection code. Works in Chrome and Safari.

function isResponsive() {
  if (document.styleSheets || (typeof window.CSSMediaRule).match(/function|object/)) {
    // find avaliable style sheets
    return [].some.call(document.styleSheets, function(css) {
      if (!css.cssRules) {
        return false;
      }

      // find avaliable rules
      return [].some.call(css.cssRules, function(rule) {
        if (rule instanceof CSSMediaRule) {
          return [].some.call(rule.media, function(media) {
            return !media.match(/print/i);
          });
        }
      });
    });
  }
  // There's no avaliable style sheet, or the browser doesn't support media queries
  return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM