您可以使用window.orientation
属性来检测设备的旋转方向。该属性返回一个表示设备方向的数字值,其中0表示纵向(肖像)模式,90表示横向(风景)模式,并且-90表示旋转了270度的风景模式。例如,以下代码将检测当前设备的方向并输出相应的消息:
if (window.orientation === 0) {
console.log("Device is in portrait mode");
} else if (window.orientation === 90) {
console.log("Device is in landscape mode with the screen rotated to the left");
} else if (window.orientation === -90) {
console.log("Device is in landscape mode with the screen rotated to the right");
}
请注意,该属性需要设备支持方向传感器,并且在某些浏览器中可能已被弃用。