我在 http://labnol.blogspot.com/2006/12/allow-site-visitors-to-change-font.html 找到了一些代码允许人们更改字体大小并使其适应使用按钮。
<html>
<head>
<script language="JavaScript" type="text/javascript">
function changeFontSize(inc)
{
var p = document.getElementsByTagName('*');
for(n=0; n<p.length; n++) {
if(p[n].style.fontSize) {
var size = parseInt(p[n].style.fontSize.replace("px", ""));
} else {
var size = 16;
}
p[n].style.fontSize = size+inc + 'px';
}
}
</script>
</head>
<body>
<basefont size=3/>
<p>
asdf
hhui
jnj
ghvt
</p>
<input type="button" value="+" onclick="changeFontSize(1)" />
<input type="button" value="-" onclick="changeFontSize(-1)" />
</body>
</html>
我知道浏览器的一些功能,例如使用 ctrl 鼠标滚轮来更改字体大小。
我有一些问题...
1) 我怎样才能发现常量 16 应该是什么而不是将其编码? 2) 无论如何都会导致字体更改影响此页面链接到的页面?
在另一条脉络上。如果使用鼠标滚轮之类的东西来更改字体大小,我的浏览器 (Firefox) 会在每次访问页面时记住字体大小,即使在浏览器的新执行中也是如此。 Java 是否可以访问其他位置来设置/发现此信息?
最佳答案
这是一个 JavaScript 函数,您可以使用它来计算 1em 的大小(以像素为单位):
function getEmSize(el) {
// If you pass in an element ID then get a reference to the element
if (typeof el == "undefined") el = document.documentElement;
var tempDiv = document.createElement("DIV");
tempDiv.style.height = 1 + "em";
// Just in case the content of "el" takes up it's container's height :)
tempDiv.style.marginTop = -1 + "em";
el.appendChild(tempDiv);
var emSize = tempDiv.offsetHeight;
el.removeChild(tempDiv);
return emSize;
}
我还写了一篇关于 Changing Text Size On Click 的文章.只需确保通过 cookie 或 localStorage 保存首选项即可。
希望有用。
关于javascript - HTML JavaScript 字体大小更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3566629/