因此,当用户使用 Mac 时,我尝试将“关闭”按钮移至左侧,而当用户使用 PC 时将其移至右侧。现在我通过检查用户代理来完成它,但它很容易被欺骗而无法进行可靠的操作系统检测。有没有可靠的方法来检测浏览器运行的操作系统是 Mac OS X 还是 Windows?如果没有,有什么比用户代理嗅探更好?
使用 JavaScript 或 jQuery 检测 Mac OS X 或 Windows 计算机的最佳方法
该window.navigator.platform时的userAgent字符串改变没有欺骗性质。如果我将 userAgent 更改为 iPhone 或 Chrome Windows,我在 Mac 上进行了测试,navigator.platform仍然是 MacIntel。
该属性也是只读的
我可以想出下表
Mac电脑
Mac68K
麦金塔 68K 系统。
MacPPC
Macintosh PowerPC 系统。
MacIntel
麦金塔英特尔系统。iOS 设备
iPhone
iPhone。
iPod
iPod 触摸。
iPad
iPad。
现代 mac 回归,navigator.platform == "MacIntel"
但为了提供一些“未来证明”,不要使用精确匹配,希望它们会变成类似MacARM
或MacQuantum
将来的东西。
var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;
包括也使用“左侧”的 iOS
var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);
由于大多数操作系统使用右侧的关闭按钮,因此当用户使用 MacLike 操作系统时,您只需将关闭按钮向左移动即可,否则如果将其放在最常见的一侧,即右侧,则没有问题。
setTimeout(test, 1000); //delay for demonstration
function test() {
var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
if (mac) {
document.getElementById('close').classList.add("left");
}
}
#window {
position: absolute;
margin: 1em;
width: 300px;
padding: 10px;
border: 1px solid gray;
background-color: #DDD;
text-align: center;
box-shadow: 0px 1px 3px #000;
}
#close {
position: absolute;
top: 0px;
right: 0px;
width: 22px;
height: 22px;
margin: -12px;
box-shadow: 0px 1px 3px #000;
background-color: #000;
border: 2px solid #FFF;
border-radius: 22px;
color: #FFF;
text-align: center;
font: 14px"Comic Sans MS", Monaco;
}
#close.left{
left: 0px;
}
<div id="window">
<div id="close">x</div>
<p>Hello!</p>
<p>If the "close button" change to the left side</p>
<p>you're on a Mac like system!</p>
</div>
http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/
就这么简单:
function isMacintosh() {
return navigator.platform.indexOf('Mac') > -1
}
function isWindows() {
return navigator.platform.indexOf('Win') > -1
}
这是你想要的?否则,请告诉我,我将删除此帖子。
试试这个 jQuery 插件:http : //archive.plugins.jquery.com/project/client-detect
演示: http : //www.stoimen.com/jquery.client.plugin/
这是基于 quirksmode BrowserDetect 一个 jQuery 浏览器/操作系统检测插件的包装。
对于敏锐的读者:
http : //www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html
围绕插件的更多代码位于此处:http : //www.stoimen.com/jquery.client.plugin/jquery.client.js
让我知道这个是否奏效。在StackOverflow.com 的帮助下检测 Apple 设备(Mac 计算机、iPhone 等)的方法:
截至今天,navigator.platform 的可能值列表是什么?
var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone',
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike
v7.6 release 92', 'Pike v7.8 release 517'];
// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
// Execute code
}
// If NOT on Apple device
else {
// Execute code
}
我认为MacIntel
无论硬件架构如何,所有基于 Chrome 或 Chromium 的浏览器都会回归macOS 平台。