账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    用 css3 transform 旋转来强制横屏,但 touch 方向并没有发生变化,有啥解决方案?
    30
    0

    transform: rotate(90deg);

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 任凭寂寞沸腾 普通会员 1楼

      当您使用 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,使用前需做兼容性判断。

    更多回答
    扫一扫访问手机版