【发布时间】:2014-07-28 09:30:01
【问题描述】:
我想检测设备是台式机还是移动设备或平板电脑.. 在此基础上我想更改图像目录 例如
if (getDeviceState() == 'phone') {
alert("phone");
}
else if (getDeviceState() == 'tablet') {
alert("tablet");
}
else {
alert("small-desktop");
}
我已经尝试过使用 css 和 javascript
var indicator = document.createElement('div');
indicator.className = 'state-indicator';
document.body.appendChild(indicator);
// Create a method which returns device state
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() == 'phone') {
alert("phone");
}
else if (getDeviceState() == 'tablet') {
alert("tablet");
}
else {
alert("small-desktop");
}
在css中
/* small desktop */
@media all and (max-width: 1200px) {
.state-indicator {
z-index: 2;
}
}
/* tablet */
@media all and (max-width: 768px) {
.state-indicator {
z-index: 3;
}
}
/* mobile phone */
@media all and (max-width: 360px) {
.state-indicator {
z-index: 4;
}
}
但是我对风景和肖像状态越来越有把握了..所以获得 useragent 比使用 css 更好
【问题讨论】:
-
我不是为您的问题提供完美答案的人。但我所知道的是有大量非常好的框架、jQuery 插件和其他可用于检测的方法。为什么要费心自己写?关于您的问题:在 Twitter Bootstrap 中检查它是如何完成的可能是一个想法?
-
你也可以使用像 Modernizr 这样的 JS 库来检测
标签: javascript html css ipad user-agent