繁体   English   中英

如何使用javascript检测网页是否在移动设备上响应

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

我需要使用javascript来检测页面是否响应。 在星系注释3上,以下是无响应页面和响应页面的值:

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

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

因此,如果clientWidth == screen.width就是响应性的,那么它是无响应的,这是正确的说法吗?

如您所知,响应式设计调用媒体查询中使用了一项重要功能,浏览器可以使用该功能为不同的屏幕分辨率切换替代CSS规则,以使页面“响应式”。

您可以使用document.styleSheets在Javascript中枚举CSS规则。 和CSS一样

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

将在cssRules集合中添加CSSMediaRule的一些实例。 这是我的检测代码。 适用于Chrome和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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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