h5 强制横屏

本文介绍了一种使用JavaScript根据设备方向自动调整网页元素显示方向的方法。具体实现中利用了document.documentElement.clientWidth和clientHeight属性来获取视口尺寸,并通过监听orientationchange或resize事件来实时更新元素的宽度、高度及旋转角度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  <script>
    var width = document.documentElement.clientWidth;
    var height = document.documentElement.clientHeight;
    $app = $('#app');
    if (width < height) {
      console.log(width + " " + height);
      $app.width(height);
      $app.height(width);
      $app.css('transform', 'rotate(90deg)');
      $app.css('transform-origin', `${width / 2}px ${width / 2}px`);
    }
    var evt = "onorientationchange" in window ? "orientationchange" : "resize";
    window.addEventListener(evt, function () {
      setTimeout(function () {
        var width = document.documentElement.clientWidth;
        var height = document.documentElement.clientHeight;
        $app = $('#app');
        if (width > height) {
          $app.width(width);
          $app.height(height);
          $app.css('transform', 'none');
          $app.css('transform-origin', `${width / 2}px ${width / 2}px`);
        } else {
          $app.width(height);
          $app.height(width);
          $app.css('transform', 'rotate(90deg)');
          $app.css('transform-origin', `${width / 2}px ${width / 2}px`);
        }
      }, 100)
    }, false);
  </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值