js实现手机旋转
监听设备方向变化
使用 window.addEventListener 监听 deviceorientation 事件,该事件在设备方向变化时触发。事件对象包含 alpha(绕Z轴旋转角度)、beta(绕X轴旋转角度)和 gamma(绕Y轴旋转角度)三个参数。
window.addEventListener('deviceorientation', (event) => {
const { alpha, beta, gamma } = event;
console.log(`Alpha: ${alpha}, Beta: ${beta}, Gamma: ${gamma}`);
});
处理旋转数据
根据 beta 和 gamma 的值判断设备旋转方向。beta 表示前后倾斜(-180到180),gamma 表示左右倾斜(-90到90)。通过阈值判断设备是否处于横屏或竖屏状态。
window.addEventListener('deviceorientation', (event) => {
const { beta, gamma } = event;
if (Math.abs(beta) > 45 || Math.abs(gamma) > 45) {
console.log('横屏状态');
} else {
console.log('竖屏状态');
}
});
动态调整页面布局
结合 CSS 媒体查询或 JavaScript 动态修改样式,适应横竖屏切换。例如,通过检测窗口宽高比判断屏幕方向。
function checkOrientation() {
if (window.innerHeight > window.innerWidth) {
document.body.classList.add('portrait');
document.body.classList.remove('landscape');
} else {
document.body.classList.add('landscape');
document.body.classList.remove('portrait');
}
}
window.addEventListener('resize', checkOrientation);
checkOrientation();
兼容性处理
部分浏览器可能不支持 deviceorientation 事件,需检测兼容性并回退到 orientationchange 事件或窗口大小变化监听。
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', handleOrientation);
} else {
window.addEventListener('orientationchange', () => {
console.log('Orientation changed:', window.orientation);
});
}
示例:旋转元素
根据设备旋转数据动态旋转页面元素。使用 transform: rotate 结合 gamma 值实现倾斜效果。
window.addEventListener('deviceorientation', (event) => {
const element = document.getElementById('rotatable');
element.style.transform = `rotate(${event.gamma * 2}deg)`;
});
注意事项
- iOS 13+ 需要用户授权才能获取
deviceorientation数据,需在安全上下文(HTTPS)中运行。 - 部分安卓设备可能不支持完整的
beta和gamma数据。 - 横竖屏切换时,部分浏览器可能不会触发
resize事件,需结合orientationchange监听。







