HTML JavaScript字体大小更改

时间:2010-08-25 14:02:12

标签: javascript html font-size

我在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设置/发现此信息?

2 个答案:

答案 0 :(得分:0)

这是一个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保存首选项。

希望这很有用。

答案 1 :(得分:0)

最简单的方法是将页面更改为不使用像素。如果您使用了ems,那么您只需要更改body元素的字体大小,其他所有内容都会调整。

大多数浏览器都能够更改内置的字体大小,因此如果您开始正确编码页面,这实际上没有任何好处。

相关问题