转载-js如何设置网页横屏和竖屏切换

这段HTML和JavaScript代码展示了如何监听和处理手机横竖屏切换的事件。通过`window.innerWidth`和`window.innerHeight`判断屏幕方向,并更新页面元素显示横竖屏状态。请注意,这种做法可能会影响用户的屏幕设置自由度。

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

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta http-equiv="Content-Type" content="application/xhtml+xml;charset=UTF-8" />
    5. <meta name="viewport" content="width=device-width" />
    6. <title>手机横、竖屏事件</title>
    7. <script language="javascript" type="text/javascript">
    8. //屏幕方向标识,0横屏,其他值竖屏
    9. var orientation=0;
    10. //转屏事件,内部功能可以自定义
    11. function screenOrientationEvent(){
    12.     if(orientation == 0)document.getElementById("change").value="竖";
    13.     else document.getElementById("change").value="横";
    14. }
    15. var innerWidthTmp = window.innerWidth;
    16. //横竖屏事件监听方法
    17. function screenOrientationListener(){
    18.     try{
    19.         var iw = window.innerWidth;    
    20.         //屏幕方向改变处理
    21.         if(iw != innerWidthTmp){
    22.             if(iw>window.innerHeight)orientation = 90;
    23.             else orientation = 0;
    24.             //调用转屏事件
    25.             screenOrientationEvent();
    26.             innerWidthTmp = iw;
    27.         }
    28.     } catch(e){alert(e);};
    29.     //间隔固定事件检查是否转屏,默认500毫秒
    30.     setTimeout("screenOrientationListener()",500);
    31. }
    32. //启动横竖屏事件监听
    33. screenOrientationListener();
    34. </script>
    35. </head>
    36. <body onload="screenOrientationEvent()">
    37. <input id="change" type="text" value=""/>
    38. </body>
    39. </html>

 

注:js手机横竖屏事件实现的方法(不依赖任何其他库),从客户角度是违反了用户的自定义行为的。

 

转载于:https://www.cnblogs.com/alanaZ/p/4708360.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值