使用Javascript;如何检查用户设备是否为iPhoneX?
另外,当横向放置时,如何确定iPhone的“缺口”位于哪一侧?
有一些很棒的文章:https://webkit.org/blog/7929/designing-websites-for-iphone-x/
...但是这些往往会利用在撰写本文时许多移动浏览器本身不支持的尖端功能。
最佳答案
因此,我想出了一种使用Javascript检测iPhoneX的方法。我的过程还根据用户设备的方向检查缺口的位置:
https://codepen.io/marknotton/pen/NwpgBK
(function(window){
// Really basic check for the ios platform
// https://stackoverflow.com/questions/9038625/detect-if-device-is-ios
var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
// Get the device pixel ratio
var ratio = window.devicePixelRatio || 1;
// Define the users device screen dimensions
var screen = {
width : window.screen.width * ratio,
height : window.screen.height * ratio
};
// iPhone X Detection
if (iOS && screen.width == 1125 && screen.height === 2436) {
// Set a global variable now we've determined the iPhoneX is true
window.iphoneX = true;
// Adds a listener for ios devices that checks for orientation changes.
window.addEventListener('orientationchange', update);
update();
}
// Each time the device orientation changes, run this update function
function update() {
notch();
iphoneXChecker();
}
// Notch position checker
function notch() {
var _notch = '';
if( 'orientation' in window ) {
// Mobile
if (window.orientation == 90) {
_notch = 'left';
} else if (window.orientation == -90) {
_notch = 'right';
}
} else if ( 'orientation' in window.screen ) {
// Webkit
if( screen.orientation.type === 'landscape-primary') {
_notch = 'left';
} else if( screen.orientation.type === 'landscape-secondary') {
_notch = 'right';
}
} else if( 'mozOrientation' in window.screen ) {
// Firefox
if( screen.mozOrientation === 'landscape-primary') {
_notch = 'left';
} else if( screen.mozOrientation === 'landscape-secondary') {
_notch = 'right';
}
}
window.notch = _notch;
}
})(window);
// Bespoke functions:
// The above functions have no jQuery Dependencies.
// The below code uses jQuery solely for this quick demo.
if ( window.iphoneX === true ) {
$('body').addClass('iphoneX');
}
function iphoneXChecker() {
if (window.notch == 'left') {
$('body').removeClass('notch-right').addClass('notch-left');
} else if (window.notch == 'right') {
$('body').removeClass('notch-left').addClass('notch-right');
} else {
$('body').removeClass('notch-right notch-left');
}
}
我忍不住觉得这只是一些小技巧。您可能会注意到;我的Javascript并非完全符合高标准,我敢肯定有更好/更干净的方法可以做到这一点。
我很高兴收到我未曾考虑过的问题的反馈和解决方案。
如果您只想检查iPhoneX(忽略缺口),则应执行以下操作:
https://codepen.io/marknotton/pen/MOpodJ
(function(){
// Really basic check for the ios platform
// https://stackoverflow.com/questions/9038625/detect-if-device-is-ios
var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
// Get the device pixel ratio
var ratio = window.devicePixelRatio || 1;
// Define the users device screen dimensions
var screen = {
width : window.screen.width * ratio,
height : window.screen.height * ratio
};
// iPhone X Detection
if (iOS && screen.width == 1125 && screen.height === 2436) {
alert('iPhoneX Detected!');
}
})();