我编写了一些简单的代码来侦听'orientationchange'(Safari / iOS)事件,然后尝试将div调整为新的窗口方向/大小。
问题在于调整大小和定位不按照我期望的方式工作。我想要div调整大小(使用渐变背景)并填充屏幕。我附加了屏幕抓取以突出问题。
如果有人能告诉我为什么我的代码无效,我会非常感激。
我的测试是使用Apple的iPhone模拟器,打开Safari(在模拟器上)并将其指向我的localhost,其中包含以下测试代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Div Resizing/positioning Test</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style>
.masterTemplate {
position: absolute;
left:0px;
top:0px;
background: -webkit-linear-gradient( -70deg, black 60%, navy );
border: 1px solid magenta;
overflow: hidden;
}
</style>
</head>
<body>
<div id="masterTemplate"></div>
<script>
$(document).ready( function() {
console.log("document ready");
window.addEventListener("orientationchange", onOrientationChange );
$("#masterTemplate").css( { width:window.innerWidth, height:window.innerHeight } );
$("#masterTemplate").addClass("masterTemplate");
function onOrientationChange(event) {
console.log('onOrientationChange',event);
$("#masterTemplate").removeClass("masterTemplate");
$("#masterTemplate").css({ width:window.innerWidth, height:window.innerHeight, top:"0px", left:"0px" });
$("#masterTemplate").addClass("masterTemplate");
}
} );
</script>
</body>
</html>
答案 0 :(得分:0)
这似乎不对...... - &gt; width:window.innerWidth,height:window.innerHeight。如果你想要的是给窗口的宽度和高度为什么不通过css设置它?
width: 100%;
height: 100%;
答案 1 :(得分:0)
尝试通过以下方式更改JavaScript代码来调整窗口大小:
相反
$("#masterTemplate").css( { width:window.innerWidth, height:window.innerHeight } );
使用
var clientWidth = jQuery(window).width();
var clientHeight = jQuery(window).height();
window.resizeTo( clientWidth,clientHeight )
,
其中clientWidth
和clientHeight
是宽度和高度(以像素为单位)。
或者,如果您更喜欢使用jQuery选择器,请尝试使用:
$("#masterTemplate").css( { width:jQuery(window).width(), height:jQuery(window).height() } );
答案 2 :(得分:0)
将我的头撞在砖墙上几个小时后,我似乎找到了自己的问题的答案,并希望发布它,因为它可能会帮助其他人在HTML5移动开发的早期阶段。< / p>
有时你计划的任何事情都可能涉及手动控制视口。如果您不确定Viewport是什么,那么有很多非常好的文章和配置示例,其中一个是this link!
我的问题源于我不知道在每次旋转设备后我需要重置(希望是正确的术语)视口。将以下代码添加到'orientationchange'事件处理程序中解决了我的问题:
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1.0')
我还将初始视口元配置修剪为:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">