是否可以使用 javascript 检测 iPad 或 Galaxy Tab 上浏览器方向的变化?我认为可以使用 css 媒体查询。
使用javascript检测方向的变化
IT技术
javascript
css
ipad
accelerometer
galaxy-tab
                    2021-01-26 15:20:31
                
                    
                
            
        6个回答
            更新:
你可能想看看
或普通的 JS 之一:
window.addEventListener("orientationchange", function() {
  alert(window.orientation);
}, false);
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 属性,因此如有必要,您可以使用它来确定用户是处于水平模式还是垂直模式。作为此功能的提醒:
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 对象上触发。
您还可以使用 CSS 媒体查询来确定 iPad 是处于垂直还是水平方向,例如:
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
<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>
你可以像这样使用orientationchange事件:
window.addEventListener('orientationchange', function(event) {
     /* update layout per new orientation */
});
您可以使用mediaMatch来评估 CSS 媒体查询,例如
window
    .matchMedia('(orientation: portrait)')
    .addListener(function (m) {
        if (m.matches) {
            // portrait
        } else {
            // landscape
        }
    });
CSS 媒体查询在orientationchange. 如果您希望捕获事件的结束(旋转完成时),请参阅方向更改后的移动视口高度。
来自“跨设备、跨浏览器的人像-横向检测”
这是关于找出移动设备是处于纵向模式还是横向模式;你不需要关心它的方向。据您所知,如果您将 iPad 倒置,则它处于纵向模式。
$(window).bind("resize", function(){
    screenOrientation = ($(window).width() > $(window).height())? 90 : 0;
});
90 表示横向,0 表示纵向,跨浏览器,跨设备。
window.onresize 事件随处可用,而且总是在正确的时间触发;永远不会太早,永远不会太晚。事实上,屏幕的大小也总是准确的。
JavaScript 版本是这样的,如果我错了,请纠正我。
  function getScreenOrientation() {
    screenOrientation = window.outerWidth > window.outerHeight ? 90 : 0;
    console.log("screenOrientation = " + screenOrientation);
  }
  window.addEventListener("resize", function(event) {
    getScreenOrientation();
  });
  getScreenOrientation();
我意识到没有人提到在这个线程中倒置设备时会发生什么。
window.orientation保持水平时返回 -90 或 90。垂直时返回 0 或 180。有些设备支持,有些不支持倒置。我建议,
window.addEventListener("orientationchange", function() {
  
  if ( window.orientation == 0 || window.orientation == 180) {
    // WHEN IN PORTRAIT MODE
    
  } else {
    // WHEN IN LANDSCAPE MODE
    
  }
}, false);
另请注意,台式机上的window.orientation退货undefined。
其它你可能感兴趣的问题