function getDeviceState() {
var index = parseInt(window.getComputedStyle(indicator).getPropertyValue(‘z-index’), 10);
var states = {
2: ‘small-desktop’,
3: ‘tablet’,
4: ‘phone’
};
return states[index] || ‘desktop’;
}
这样,你就一个写出更具可读性的逻辑判断:
if(getDeviceState() == ‘tablet’) {
// Do whatever
}
也许使用CSS的伪元素的content属性是个更好的方法:
.state-indicator {
position: absolute;
top: -999em;
left: -999em;
}
.state-indicator:before { content: ‘desktop’; }
/* 小屏幕桌面 */
@media all and (max-width: 1200px) {
.state-indicator:before { content: ‘small-desktop’; }
}
/* 平板 */
@media all and (max-width: 1024px) {
.state-indicator:before { content: ‘tablet’; }
}
/* 手机 */
用下面的JavaScript方法获取关键的内容:
var state = window.getComputedStyle(
document.querySelector(‘.state-indicator’), ‘:before’
).getPropertyValue(‘content’)
如何组织这些代码全看你自己了。如果你有一个全局对象,例如window.config或window.app等,你可以把这些方法放到里面。我倾向于模块化这些功能,你可以把它做成jQuery插件或JavaScript工具包。不管你如何实现,它们都是你可以信赖的、简单易用的检测用户设备的好方法。
更上一层楼
我们知道屏幕尺寸会发生变化——用户手工调整浏览器大型或手机用户调整了手机方向,所以,当这些事件发生时,我们需要让系统告诉我们。下面这段简单的代码估计是你需要的:
var lastDeviceState = getDeviceState();
window.addEventListener(‘resize’, debounce(function() {
var state = getDeviceState();
if(state != lastDeviceState) {
// 保持当前的状态
lastDeviceState = state;
// 宣告状态变化,通过自定义的DOM事件或JS 消息发布/订阅模式,
// 我喜欢后者,所有就假设使用了一个这样的工具库
publish(‘/device-state/change’, [state]);
}
}, 20));
// 用法
subscribe(‘/device-state/change’, function(state) {
if(state == 3) { // or “tablet”, if you used the object
}
});
注意,这里我使用了debounce方法来执行resize事件发生时的动作——这对于性能来说非常重要。是使用自定义DOM事件还是使用发布/订阅模式,你自由选择,因为都很简单。
我觉得这种方法非常的好。有人可能会指出使用matchMedia也可以有相同效果,但问题是你需要在CSS里和JavaScript里都使用媒体查询,而有些媒体查询语句可能会很复杂,甚至会成为你的噩梦,不如使用简单的z-index。也有人会说可以使用 window.innerWidth来判断,但这样JS里获取的属性和CSS里的媒体查询就需要相互转换了,同样也会成为你的恶魔。我的方法的好处就在于你可以用它判断其他类型的媒体查询属性,例如检查手机是横向(landscape)还是竖向(portrait)。










