javascript - 尝试使用 CSS 和 Jquery 确定设备类型未按预期工作

标签 javascript jquery html css

我正在尝试使用 CSS 和 Javascript 的混合来检测客户端设备尺寸。 [From this tutorial]我创建了一个附加到正文的元素,并为其分配了一个类,该类包含一个名为“z-index”的值,用于确定设备类型。但是,当运行以下代码时,我得到“未定义”作为响应。

我怎样才能得到一个数值而不是未定义的值?

$(document).ready(function() {

  var indicator = document.createElement('div');
  indicator.className = 'state-indicator';
  document.getElementsByTagName('body')[0].appendChild(indicator);

  function getDeviceState() {
    var index = parseInt(window.getComputedStyle(indicator).getPropertyValue('z-index'), 10);

    var states = {
      0: 'desktop',
      1: 'small-desktop',
      2: 'large-tablet',
      3: 'medium-tablet',
      4: 'phone'
    };

    return states[index];
  }

  console.log(getDeviceState());

});
/*default */

.state-indicator {
  z-index: 0;
}
@media all and (max-width: 1200px) {
  /* start of small desktop */
  .state-indicator {
    z-index: 1;
  }
}
/* end of desktop styles */

@media screen and (max-width: 991px) {
  /* start of large tablet styles */
  .state-indicator {
    z-index: 2;
  }
}
@media screen and (max-width: 767px) {
  /* start of medium tablet styles */
  .state-indicator {
    z-index: 3;
  }
}
@media screen and (max-width: 479px) {
  /* start of phone styles */
  .state-indicator {
    z-index: 4;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

最佳答案

z-index 仅适用于定位元素,如果您检查实际值是什么 autostates[parseInt('auto')] 未定义

解决眼前问题的 Css 调整:

.state-indicator {
  z-index: 0;
  position:relative;
}

因为您使用的是 jQuery,所以这里有一个稍微简单的版本,一旦获得所需的值,它也会删除该元素

$(function() {      

    function getDeviceState() {        
        var $indicator = $('<div>', {'class': 'state-indicator'});
        $('body').append($indicator);

        var index = $indicator.css('z-index');
        // got the value, so remove the test element
        $indicator.remove();
        // technically js property names can not be numeric, and will get cast to string but not all browsers will
        var states = {
          '0': 'desktop',
          '1': 'small-desktop',
          '2': 'large-tablet',
          '3': 'medium-tablet',
          '4': 'phone'
        };

        return states[index];
      }

      console.log(getDeviceState());
});

DEMO

关于javascript - 尝试使用 CSS 和 Jquery 确定设备类型未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917450/

相关文章:

javascript - Firebase:TypeError:fbRef.child 不是函数

jquery - 固定位置导航栏 slideUp slideDown 功能在向下滚动后中断

javascript - FileReader:对象不是函数

javascript - 如何将循环 JSON 对象字符串化并将其保存到文件中?

c# - jquery Ajax 响应文本 "There was an error processing the request"

javascript - jQuery 和 JS 变量到 fadeOut()

javascript - cordova/phonegap 应用程序 - 从服务器加载 js css 和 html

php - 出现 "You have an error in your SQL syntax"错误 - PHP、MySQL

javascript - 使用 axios 将数据发送到输入 ReactJS 中的每个更改

javascript - jPlayer - 使用 setMedia() 设置媒体 URL