我正在开发一堆以未知窗口大小为目标的小型 Web 应用程序。为了解决这个问题,我正在开发非常大的布局并根据窗口大小缩放它们。
但是我的解决方案有一个不便之处。当我调整所有内容的大小时,事情变得有点不合适(主要是在缩放文本时)并且很明显。我的代码非常简单,我页面中的所有内容都是绝对定位的,所以我只需获取比例因子并将其应用于页面中每个 div/img/span/input 的所有位置和宽度/高度。代码如下:
function resize()
{
var wh = $(window).height();
var h = maxHeight;
var ww = $(window).width();
var w = maxWidth;
var wProp = ww / w;
var hProp = wh / h;
if (wProp < hProp) prop = wProp;
else prop = hProp;
if (prop > 1) prop = 1;
console.log(prop);
$("div").each (applyNewSize);
$("img").each (applyNewSize);
$("span").each (applyNewSize);
$("input").each (applyNewSize);
}
//this is run when the page is loaded
function initializeSize (i)
{
this.oX = $(this).position().left;
this.oY = $(this).position().top;
this.oW = $(this).width();
this.oH = $(this).height();
if ($(this).css("font-size") != undefined)
{
this.oFS = Number($(this).css("font-size").split("px")[0]);
}
}
function applyNewSize (i)
{
if (this.oFS != undefined) $(this).css("font-size", Math.round(this.oFS * prop) + "px");
$(this).css("left", Math.round(this.oX * prop) + "px");
$(this).css("top", Math.round(this.oY * prop) + "px");
$(this).width(Math.round(this.oW * prop));
$(this).height(Math.round(this.oH * prop));
}
这个问题在过去的一周里一直折磨着我。您对此有任何解决方法或解决方案吗?
最佳答案
我建议您阅读响应式网页设计。
它可以用 % 代替精确的像素:
<div class="container">
<section>
THIS IS THE SECTION
</section>
</div>
CSS::
.container{
width: 80%; // 80% instead pixels
background: gainsboro;
border: 3px inset darkgrey;
height: 200px;
margin:auto;
text-align:center;
}
section{
width: 80%; // 80% instead pixels
height: 80%; // 80% instead pixels
background: darkgrey;
margin:auto;
}
然后您也可以使用媒体查询来重新分配 block 或在不同的宽度上应用不同的样式:
关于javascript - 动态调整网页大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675376/