【发布时间】:2017-04-12 14:53:32
【问题描述】:
我有这个具有固定宽度和高度的网络单页应用程序。我需要一直适应页面。我在扩展它时遇到问题。
如果我只根据它来缩放它,它就可以完美地工作。
var app = $('body');
var appWidth = app.width();
var currentWidth = window.innerWidth;
var ratio = currentWidth / appWidth;
app.css('zoom', ratio);
$(window).resize(function() {
currentWidth = window.innerWidth;
ratio = currentWidth / appWidth;
app.css('zoom', ratio);
console.log(ratio);
});
html {
background-color: red;
}
body {
background-color: gray;
width: 960px;
height: 540px;
position:relative;
}
p{
position:absolute;
bottom:0;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<h1>This content shrinks once it's scaled</h1>
<img src="http://lorempixel.com/400/200/" />
<p>This shouldn't get cut off once it's scaled</p>
</body>
但是,我试图从它的高度和宽度实现缩放,而无需拉伸以使其正确地适合页面。我知道在相同的情况下可能会有一些额外的间距,但只要没有拉伸就可以了。
下面的代码是我所得到的。如您所见,一旦从两侧缩放,它就不能很好地缩放。
var app = $('body');
var appWidth = app.width();
var appHeight = app.height();
var lastWidth = window.innerWidth;
var lastHeight = window.innerHeight;
var currentWidth;
var currentHeight;
var ratio;
app.css('zoom', ratio);
fitToPage();
$(window).resize(function() {
fitToPage();
});
function fitToPage() {
currentWidth = window.innerWidth;
currentHeight = window.innerHeight;
if(currentWidth !== lastWidth && currentHeight !== lastHeight){
console.log('both width and height changed');
ratio = currentWidth / appWidth;
app.css('zoom', ratio);
lastWidth = window.innerWidth;
lastHeight = window.innerHeight;
}
else if (currentWidth !== lastWidth){
console.log('width changed');
ratio = currentWidth / appWidth;
app.css('zoom', ratio);
lastWidth = window.innerWidth;
}
else if (currentHeight !== lastHeight){
console.log('height changed');
ratio = currentHeight / appHeight;
app.css('zoom', ratio);
lastHeight = window.innerHeight;
}
}
html {
background-color: red;
}
body {
background-color: gray;
width: 960px;
height: 540px;
position:relative;
}
p{
position:absolute;
bottom:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<h1>This content shrinks once it's scaled</h1>
<img src="http://lorempixel.com/400/200/" />
<p>This shouldn't get cut off once it's scaled</p>
</body>
【问题讨论】:
-
我看看。首先,它似乎永远不会进入你的最后一个 else-if 语句。
-
哦,对不起,我想我已经修改了代码。如果你再次打开它,我将它恢复回来它现在应该可以工作了。 output.jsbin.com/sejabi
-
这是您要寻找的行为:codepen.io/gc-nomade/full/VmMPGd 吗?
标签: jquery css zooming aspect-ratio