是否可以在设备旋转时避免在 Safari for iOS 中过渡到横向 View ?
iOS Safari 有“orentationchange”事件,我试图拦截它并禁用默认行为,如下所示:
<html>
<head>
<script type="text/javascript">
function changeOrientation(event) {
alert("Rotate");
event.preventDefault();
}
</script>
</head>
<body onorientationchange="changeOrientation(event);">
PAGE CONTENT
</body>
</html>
但是在我的 iPhone 上测试页面时,当我旋转设备时会显示警告,但 View 切换为横向。似乎 event.preventDefault() 不会停止旋转。
有没有办法阻止这种行为?
最佳答案
Jonathan Snook有解决这个问题的方法。在他的幻灯片中 here ,他展示了如何(某种程度上)锁定纵向(请参阅幻灯片 54 和 55)。
这些幻灯片中的 JS 代码:
window.addEventListener('orientationchange', function () {
if (window.orientation == -90) {
document.getElementById('orient').className = 'orientright';
}
if (window.orientation == 90) {
document.getElementById('orient').className = 'orientleft';
}
if (window.orientation == 0) {
document.getElementById('orient').className = '';
}
}, true);
和CSS:
.orientleft #shell {
-webkit-transform: rotate(-90deg);
-webkit-transform-origin:160px 160px;
}
.orientright #shell {
-webkit-transform: rotate(90deg);
-webkit-transform-origin:230px 230px;
}
我试图让它在 iPhone 上为landscape 工作,但它从来没有看起来 100% 正确。然而,我接近了以下 jQueryian 代码。这将在 onready 函数内。另请注意:这是在“保存到主屏幕”上下文中,我认为这改变了 tranform-origin 的位置。
$(window).bind('orientationchange', function(e, onready){
if(onready){
$(document.body).addClass('portrait-onready');
}
if (Math.abs(window.orientation) != 90){
$(document.body).addClass('portrait');
}
else {
$(document.body).removeClass('portrait').removeClass('portrait-onready');
}
});
$(window).trigger('orientationchange', true); // fire the orientation change event at the start, to make sure
还有 CSS:
.portrait {
-webkit-transform: rotate(90deg);
-webkit-transform-origin: 200px 190px;
}
.portrait-onready {
-webkit-transform: rotate(90deg);
-webkit-transform-origin: 165px 150px;
}
希望能帮助人们接近预期的结果...
关于javascript - 防止 iOS Safari 中的方向改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5298467/