监听设备方向变化?分享 1 段优质 JS 代码片段!

大家好,我是大澈!

本文约 700+ 字,整篇阅读约需 1 分钟。

每日分享一段优质代码片段。

今天分享一段 JS 代码片段,用于在H5端监听设备方向的变化。

老规矩,先阅读代码片段并思考,再看代码解析再思考,最后评论区留下你的见解!

js 复制代码
$(document).ready(function() {
    function handleOrientationChange() {
        if (window.orientation === 0 || window.orientation === 180) {
            // Portrait
            $('body').css('transform', 'rotate(90deg)');
        } else {
            // Landscape
            $('body').css('transform', 'rotate(0deg)');
        }
    }

    // Listen for orientation changes
    $(window).on("orientationchange", handleOrientationChange);

    // 页面加载时进行初始方向检测
    handleOrientationChange();
});

分享原因

这段代码提供了一个实用的解决方案,可以检测设备方向的变化并根据方向更改页面的样式。

这在移动设备上非常有用,因为用户可能会旋转他们的设备来更好地查看内容。

代码解析

  1. $(document).ready(function() { ... });

确保页面DOM完全加载后再运行内部代码。

这是一个jQuery的基础方法。

2. if (window.orientation === 0 || window.orientation === 180)

检查设备方向是否为竖屏模式(0度或180度)。

这里是代码最关键的地方。

3. $('body').css('transform', 'rotate(90deg)');

如果是竖屏模式,旋转页面90度。否则(横屏模式),恢复正常的旋转角度(0度)。

这里的代码可以自定义,按项目实际需求来写即可,就是在旋转时打算要做的操作或者要调整的样式。

4. $(window).on("orientationchange", handleOrientationChange);

监听窗口的orientationchange事件,当设备方向变化时调用handleOrientationChange函数。

  • end -
相关推荐
摘星编程6 小时前
React Native for OpenHarmony 实战:Linking 链接处理详解
javascript·react native·react.js
胖者是谁7 小时前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder7 小时前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
摘星编程8 小时前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
摘星编程9 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5569 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20229 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程9 小时前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity9 小时前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
济61710 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript