我正在尝试使用 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
仅适用于定位元素,如果您检查实际值是什么 auto
和 states[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());
});
关于javascript - 尝试使用 CSS 和 Jquery 确定设备类型未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917450/