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

ⅰ亾dé卋堺 提交于 2020-01-24 16:49:44

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/20717056/how-to-use-javascript-to-detect-whether-a-web-page-is-responsive-on-mobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!