transform: rotate(90deg);
当您使用 CSS3 的 transform: rotate() 属性强制横屏时,设备的物理方向虽然看起来变成了横屏,但实际上浏览器对 touch 事件的认知并没有改变,它仍然基于原始的设备方向。这意味着在处理触摸、滑动等交互事件时,坐标系仍然是竖屏状态下的坐标系。
解决这个问题的一种方案是通过 JavaScript 来监听并转换触摸事件的坐标:
```javascript window.addEventListener('DOMContentLoaded', function() { window.addEventListener('touchstart', handleTouchStart, false); window.addEventListener('touchmove', handleTouchMove, false);
var initialRotationDegree = 90; // 根据你的旋转角度来设定
var isRotated = true; // 判断是否进行了旋转
function handleTouchStart(event) {
if (isRotated) {
event.touches[0].clientX -= window.innerWidth / 2;
event.touches[0].clientY -= window.innerHeight / 2;
event.touches[0].clientX *= Math.cos(initialRotationDegree * Math.PI / 180);
event.touches[0].clientY *= Math.sin(initialRotationDegree * Math.PI / 180);
}
}
function handleTouchMove(event) {
if (isRotated) {
event.touches[0].clientX -= window.innerWidth / 2;
event.touches[0].clientY -= window.innerHeight / 2;
event.touches[0].clientX *= Math.cos(initialRotationDegree * Math.PI / 180);
event.touches[0].clientY *= Math.sin(initialRotationDegree * Math.PI / 180);
}
}
}); ```
上述代码示例中,我们首先监听了 touchstart 和 touchmove 事件,并根据旋转角度调整了触摸点的坐标。但请注意,这只是一个简化的示例,实际应用中可能需要更复杂的计算和兼容性处理。
另外,现代浏览器提供了 screen.orientation
API,可以用来检测和控制屏幕方向,结合这个API也许能更好地实现您的需求,例如锁定屏幕方向为横屏:
javascript
if ('orientation' in screen) {
screen.orientation.lock('landscape').catch(function() {
// 错误处理,如浏览器不支持或用户拒绝权限
});
}
不过,请注意并非所有设备和浏览器都支持此API,使用前需做兼容性判断。