Web开发中管理ipad屏幕的方向变化
2014-03-24 19:01
405 查看
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-primaryPortrait模式, 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的值? 呵呵,确实不能。
相关文章推荐
- Android 程式开发:(八)处理屏幕方向的变化 —— 8.4控制Activity的显示方向
- Android 程式开发:(八)处理屏幕方向的变化 —— 8.2在“变化”中保存状态信息
- [Web开发] IE8 中 session 管理的变化
- javaweb开发中的权限管理的方法
- 手机Web开发 jQuery 获取屏幕高度、宽度
- WEB系统技术开发方向
- web工作流管理系统开发之二 工作流引擎
- web工作流管理系统开发之七 最新的dtd格式校验修改
- 投票管理系统案例-Java Web开发实例
- JQuery移动页面开发之屏幕方向改变与滚屏的实现
- web工作流管理系统开发之四 自定义表单
- java web开发的毕业设计论文管理系统
- iOS开发中屏幕旋转至一个方向后再手动设置屏幕旋转至该方向无效问题
- JavaWeb项目开发案例精粹-第6章报价管理系统-07View层
- Web开发中的风险管理
- web开发管理环境构筑
- (Web)应用软件开发和管理的基本原则
- Android 屏幕方向改变全屏和 actionBar 变化处理
- web工作流管理系统开发之一 工作流概念
- Windows Mobile 开发识别屏幕方向的应用程序