如何使用javascript、css检测浏览器/设备?
我想检测设备是台式机、移动设备还是平板电脑。。在此基础上,我想更改图像目录 例如 我尝试过使用css和javascript如何使用javascript、css检测浏览器/设备?,javascript,html,css,ipad,user-agent,Javascript,Html,Css,Ipad,User Agent,我想检测设备是台式机、移动设备还是平板电脑。。在此基础上,我想更改图像目录 例如 我尝试过使用css和javascript var indicator = document.createElement('div'); indicator.className = 'state-indicator'; document.body.appendChild(indicator); // Create a method wh
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;
}
}
但我对横向和横向状态有疑问。因此,获得用户代理比使用css更好。只使用JS可以检查window.outerHeight和window.outerWidth。 因此,结合不同的尺寸,您可以定义设备类型。
此外,您还可以解析navigator.userAgent,它包含用户浏览器的名称。您可以使用
device.js
源代码和示例可以从以下链接获得
使用以下方法获取设备类型
device.mobile()
device.tablet()
使用以下命令获取方向:
device.landscape()
device.portrait()
HTML具有
用户代理
字段以发送设备信息:
PC
mozilla/5.0(windowsnt 6.3;wow64)applewebkit/537.36(khtml,像gecko)chrome/36.0.1985.125 safari/537.36
iPhone
Mozilla/5.0(iPhone;CPU iPhone OS 5_1,如Mac OS X)AppleWebKit/534.46(KHTML,如Gecko)Mobile/9B176微传感器/4.3.2
Windows Phone
UCWEB/2.0(Windows;U;wds7.10;zh CN;诺基亚900)U2/1.0.0 UCBrowser/8.6.0.199 U2/1.0.0 Mobile
var ua = navigator.userAgent.toLowerCase();
//check the device like this
isChrome = ua.indexOf("chrome") > -1
我不是那个能为你的问题给出完美答案的人。但我所知道的是,有大量非常好的框架、jQuery插件和其他方法可用于检测。为什么要写你自己的呢?关于你的问题:也许可以在Twitter引导中检查它是如何完成的?试试这个:你可以使用JS库(比如Modernizer)来检测它
var ua = navigator.userAgent.toLowerCase();
//check the device like this
isChrome = ua.indexOf("chrome") > -1