那将是这样的(在 Chrome 和 IE 中测试);它适应页面加载和重新加载时的视口,但不适应随后的视口调整大小和缩放。
<!DOCTYPE HTML>
<HTML>
<HEAD>
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=ISO-8859-1">
<META NAME="viewport" CONTENT="width=device-width, initial-scale=1.0">
<STYLE TYPE="text/css">
BODY {font-size: 2vw;}
DIV {width: 50vw; height: 66vh; background-color: pink; overflow: hidden;}
H1 {font-size: 200%; font-weight: bold; margin-bottom: -.5vw}
@media screen and (min-width: 500px) {H1 {color: blue;}}
H2 {font-size: 4vmin; font-style: italic;}
P {font-size: 100%; line-height: 1.5em;}
</STYLE>
<SCRIPT>
function fixedSizes()
{
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientheight;
var units = {vw: w / 100, vh: h / 100, vmin: (w > h ? h : w) / 100, vmax: (w > h ? w : h) / 100};
var sheet = addSheet();
for (var s = 0; s < document.styleSheets.length - 1; s++)
{
var rules = document.styleSheets[s].cssRules || document.styleSheets[s].rules;
for (var r = 0; r < rules.length; r++)
{
var rule = rules[r];
if (rule.type == CSSRule.STYLE_RULE)
{
var selector = rule.selectorText;
var styles = rule.style.cssText.match(/[\w-]+\s?:\s?-?[\d\.]+(vw|vh|vmin|vmax)/g);
for (var t = 0; styles && t < styles.length; t++)
{
var style = styles[t];
var prop = style.match(/^[\w-]*/)[0];
var unit = style.match(/(vw|vh|vmin|vmax)$/)[0];
var val = parseFloat(style.match(/-?[\d\.]+(vw|vh|vmin|vmax)/)[0]) * units[unit];
addStyle(sheet, selector, prop + ": " + val + "px");
}
}
}
}
function addSheet()
{
var s = document.createElement("style");
s.type = "text/css";
s.rel = "stylesheet";
s.media = "screen";
document.getElementsByTagName("head")[0].appendChild(s);
return(document.styleSheets[document.styleSheets.length - 1]);
}
function addStyle(sheet, selector, style)
{
if (sheet.addRule)
{
sheet.addRule(selector, style);
}
else if (sheet.insertRule)
{
sheet.insertRule(selector + " { " + style + " }");
}
}
}
if (CSSRule)
{
if (document.addEventListener)
{
document.addEventListener("DOMContentLoaded", fixedSizes, false);
}
else if (window.attachEvent)
{
window.attachEvent("onload", fixedSizes);
}
}
</SCRIPT>
</HEAD>
<BODY>
<DIV>
<H1>Viewport Units</H1>
<H2>Converted to Pixel Values</H2>
<P>Probably the best way to do this for fonts,<BR>is to set the font sizes as percentages,<BR>
and then have javascript change the BODY font size.</P>
</DIV>
</BODY>
</HTML>
只是为了解释发生了什么:这会检查当前视口大小,然后遍历所有样式表,查找在视口单位中设置了值的属性,将值转换为像素,并将转换后的 css 规则添加到新样式表中附加在其他样式表之后。
当然,如果只有少数样式需要更新,您可以将它们放在一个单独的样式表中,让脚本只查看这些样式。或者您甚至可以逐字添加样式,例如:
addStyle(document.styleSheets[0], "H1", "font-size: " + w * 0.04 + "px");
addStyle(document.styleSheets[0], "P", "font-size: " + w * 0.02 + "px");
另外,不要在媒体查询中设置任何大小;这会在调整大小和缩放时改变布局。