• Web开发中管理ipad屏幕的方向变化


    Web开发中,我们会遇到在手机垂直或水平视角时展示不同状态的情况。下面我来总结一下检测移动设备方向变化的一些方法。

    1 使用javascript

    直接看代码:

    <script type="text/javascript">
     window.onorientationchange = function () {
    
        if ( orientation == 0 ) {
         alert ('Portrait模式, Home键在下边');
        }
        else if ( orientation == 90 ) {
         alert ('Landscape模式, Home键在右边');
        }
        else if ( orientation == -90 ) {
         alert ('Landscap模式, Home键在左边');
        }
        else if ( orientation == 180 ) {
         alert ('Portrait模式, Home键在上边');
        }
     }
    </script>

    原理很简单,采用window的onorientationchange的处理。每次屏幕视角方向改变时,都会触发onorientationchange事件,我们通过读取orientation属性来检测屏幕的方向(如果在firefox下,则为screen.orientation,如果是window phone IE11,则属性前都要加上ms前缀,如msOrientation,MSOrientationChange),不过这里需要注意的是,文档加载时并不会触发onorientationchange事件。因此,如果需要在文档加载时确定文档的方向,可将orientationChangeHandler()函数赋给onload事件。

    $(document).ready(function() {
        $(window).on('orientationchange', function(event) {
            //handle orientation change
        });
    });

    2 CSS 检测

    css media 查询中可以检测设备的视角方向,示例代码如下:

    @media screen and (orientation: portrait) {
     //your style    
    }
    
    @media screen and (orientation: landscape) {
    // your style   
    }

    你同样可以通过条件注释添加对不同视角的css文件引用:

    <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
    <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">

    3 阻止屏幕方向变化 (仅在firefox和ie11中支持)

    如果我们要阻止屏幕方向的变化,可以使用Screen.lockOrientation()(ie11中为msLockOrientation)方法。

    Screen.lockOrientation() 方法接受屏幕的方向字符串或字符串数组为参数,可选参数为:

    • portrait-primary 
      Portrait模式, Home键在下边
    • portrait-secondary
      Portrait模式, Home键在上边
    • landscape-primary
      Landscape模式, Home键在右边
    • landscape-secondary
      Landscap模式, Home键在左边
    • portrait:所有portrait模式
    • landscape:所有landscape模式
    • default:浏览器默认模式,根据屏幕分辨率决定,如1280*800为landscape模式,800*1280为portrait模式

    示例代码:

    var lockOrientation = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;
    
    if (lockOrientation("landscape-primary")) {
      // orientation was locked
    } else {
      // orientation lock failed
    }
    //参数可同样为字符串数组
    if (lockOrientation(["landscape-primary", "landscape-secondary"])) {
      // orientation was locked
    } else {
      // orientation lock failed
    }

    如果要解除锁定的话,可以使用Screen.unlockOrientation

    能否使用javascript动态设定屏幕方向? 很遗憾,不能。设置orientation的值? 呵呵,确实不能。

  • 相关阅读:
    Delphi Try Except 实例
    如何有效地让一个“ParentFont = False”子控件使用与父母相同的字体名称?
    WPF的本质:数据和行为
    WPF-触发器
    WPF TextBox 验证输入
    wpf数据绑定更新通知
    asp.net *.ashx类型的文件使用说明
    asp.net 定时间点执行任务的简易解决办法
    asp.net 页面延时五秒,跳转到另外的页面
    Asp.net 基于Cookie简易的权限判断
  • 原文地址:https://www.cnblogs.com/jackz001/p/3621600.html
Copyright © 2020-2023  润新知