使用javascript检测方向的变化

man*_*j82 23 javascript css accelerometer ipad galaxy-tab

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

mpl*_*jan 26

更新:

你可能想看看

jQuery移动方向更改

或简单的JS:

window.addEventListener("orientationchange", function() {
  alert(window.orientation);
}, false);
Run Code Online (Sandbox Code Playgroud)

MDN:

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

较老的答案

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

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

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)
Run Code Online (Sandbox Code Playgroud)

旋转设备时,还会在窗口对象上触发orientationchange事件.

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

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

  • 我发现这个:已弃用。不适用于新网站,从这里开始 https://developer.mozilla.org/en-US/docs/Web/API/Window/orientationchange_event May-b 这个答案应该更新。 (2认同)

CSS*_*ner 12

在 2022 年,您应该侦听更改事件,而不是添加窗口方向更改侦听器(由于已弃用,不建议使用侦听器screen.orientation) :

if (screen.orientation) { // Property doesn't exist on screen in IE11   
    screen.orientation.addEventListener("change", callback);
}
Run Code Online (Sandbox Code Playgroud)

现在除了 IE 和 Safari 之外的所有浏览器都支持它。screen(这是IE11的截图:

在此输入图像描述

...请注意,IE11orientation不支持该属性)screen

屏幕方向 API 有完整的文档记录。主要焦点是ScreenOrientation接口,它扩展了Screen. 以下是 orientation属性的2 个屏幕截图Screen,显示了angleAndroid 设备上从 0(纵向)到 90(横向)的变化:

在此输入图像描述

在此输入图像描述


Gaj*_*jus 9

您可以使用mediaMatch来评估 CSS 媒体查询,例如

window
    .matchMedia('(orientation: portrait)')
    .addListener(function (m) {
        if (m.matches) {
            // portrait
        } else {
            // landscape
        }
    });
Run Code Online (Sandbox Code Playgroud)

CSS 媒体查询在orientationchange. 如果您希望捕获事件的结束(旋转完成时),请参阅方向更改后的移动视口高度


小智 6

您可以使用orientationchange事件,如下所示:

window.addEventListener('orientationchange', function(){
     /* update layout per new orientation */
});
Run Code Online (Sandbox Code Playgroud)