使用javascript检测方向的变化 [英] Detect change in orientation using javascript

查看:41
本文介绍了使用javascript检测方向的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 javascript 检测 iPad 或 Galaxy Tab 上浏览器的方向变化?我认为可以使用 css 媒体查询.

Is it possible to detect change in orientation of the browser on the iPad or Galaxy Tab using javascript? I think it's possible using css media queries.

推荐答案

更新:

你可能想看看

jQuery 移动方向改变

或者普通的JS:

window.addEventListener("orientationchange", function() {
  alert(window.orientation);
}, false);

MDN:

window.addEventListener("orientationchange", function() {
    alert("the orientation of the device is now " + screen.orientation.angle);
});

<小时>

旧答案

http://www.nczonline.net/blog/2010/04/06/ipad-web-development-tips/

iPad 上的 Safari 确实支持 window.orientation 属性,因此如有必要,您可以使用它来确定用户是处于水平模式还是垂直模式.作为此功能的提醒:

Safari on the iPad does support the window.orientation property, so if necessary, you can use that to determine if the user is in horizontal or vertical mode. As reminder of this functionality:

window.orientation is 0 when being held vertically
window.orientation is 90 when rotated 90 degrees to the left (horizontal)
window.orientation is -90 when rotated 90 degrees to the right (horizontal)

当设备旋转时,还有一个orientationchange事件会在window对象上触发.

There is also the orientationchange event that fires on the window object when the device is rotated.

您还可以使用 CSS 媒体查询来确定 iPad 是处于垂直还是水平方向,例如:

You can also use CSS media queries to determine if the iPad is being held in vertical or horizontal orientation, such as:

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

<小时>

http://www.htmlgoodies.com/beyond/webmaster/toolbox/article.php/3889591/Detect-and-Set-the-iPhone--iPads-Viewport-Orientation-Using-JavaScript-CSS-and-Meta-Tags.htm

<script type="text/javascript">
var updateLayout = function() {
  if (window.innerWidth != currentWidth) {
    currentWidth = window.innerWidth;
    var orient = (currentWidth == 320) ? "profile" : "landscape";
    document.body.setAttribute("orient", orient);
    window.scrollTo(0, 1);
  }
};

iPhone.DomLoad(updateLayout);
setInterval(updateLayout, 400);
</script>

这篇关于使用javascript检测方向的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆