使用 HTML 和 JavaScript 动态调整字体大小






4.50/5 (5投票s)
介绍了一种构建网页的方法,该方法使用户能够动态更改字体大小。

引言
许多网页都可以受益于用户能够动态更改字体大小的功能。本文介绍了一种使用 HTML 和 JavaScript 构建网页的方法,该方法提供了该功能。
背景
很多时候,我发现自己在 Internet Explorer 中使用 Ctrl-Plus 快捷键来增大网页字体的大小。不幸的是,该快捷键会增大所有网页组件(例如,图形、文本框等)的大小,而其中一些是我不希望增大的。
提供仅增大网页文本选定部分字体大小的功能,需要一些相对高级的 JavaScript 与所有网页底层的文档对象模型 (DOM) 进行交互。但是,一旦掌握,开发该方法就相对直接。
Using the Code
我的网站的相关目录结构是
GGGustafson
CSS
CSS.css
Images
favicon.ico
Lenna.png
Melitta_teapot.png
Utah_teapot.png
ValidXHTML10.png
Scripts
control_font_size.js
cookies.js
next_page.js
Default.html
请注意,我正在 Microsoft Office Live (MSOL) 上托管我的网站。MSOL 要求网页为 ASPX 或 HTML 页面。对于本文,我将使用下载的源代码 `DynamicFontSize` 中的 HTML 页面。但是,如果读者使用 Visual Studio 构建网站页面,请选择 ASPX 页面。定义新页面后,您可以根据需要删除 Visual Studio 自动生成的 `aspx.cs` 和 `designer.cs` 页面。您也可以将网页扩展名从 `.aspx` 更改为 `.html`(在下面的对话框中回答“是”)。
variable_font 类
为了限制文本字体大小仅针对特定的 HTML 元素,我们需要一种机制来识别我们希望允许调整大小的文本元素。我选择为每个要参与调整大小的元素分配一个名为 `variable_font` 的类。
首先,在 CSS 文件中,为 `variable_font` 定义一个选择器。
.variable_font
{
font-size:13pt;
}
此规则为所有应用了该类的元素设置了默认字体大小。请注意,此处选择的值应与 `control_font_size` 脚本顶部声明的 `DEFAULT_FONT_SIZE` 全局变量的值相同。
然后,将该类分配给将参与文本字体大小调整的每个元素。例如:
<p class="variable_font" ></p>
此类可应用于任何允许字体大小属性的元素(例如,`input`、`p`、`td`、`span` 等)。
初始化
在窗口加载时,必须调用 `initialize_font_size` 函数。出于我们的目的,我将简单地将其附加为 `body onload` 事件处理程序。
<body onload="initialize_font_size('CSS.css', '.variable_font');">
`initialize_font_size` 函数在 `control_font_size` 脚本中找到。
// ********************************************* initialize_font_size
/// <summary>
/// initializes the variable 'variable_font_rule' to point to the
/// rule that controls the font size for all elements that are
/// declared as "class='selector'" in the cascading style sheet
/// named 'css_sheet_name'; reads a cookie to determine the
/// current font size; sets all such elements to the default font
/// size, either read from the cookie or specified by the global
/// variable DEFAULT_FONT_SIZE
/// </summary>
///
/// <param name="css_sheet_name">
/// a string containing the name of the cascading style sheet
/// file name, including the extension
/// </param>
///
/// <param name="selector">
/// a the string containing the selector (class name), found in
/// the specified cascading style sheet; it must include the
/// selector prefix (i.e., '.' for classes)
/// </param>
///
function initialize_font_size ( css_sheet_name,
selector )
{
if ( document.styleSheets && css_sheet_name && selector )
{
var done = false;
var found = false;
var i = 0;
var sheet_rules;
var sheets = document.styleSheets;
var the_rules = new Array();
css_sheet_name = css_sheet_name.toLowerCase ( );
i = 0;
done = ( i >= sheets.length );
while ( ! ( done || found ) )
{
var sheet_name = sheets [ i ].href.substring (
sheets [ i ].href.lastIndexOf ( '/' ) + 1 ).
toLowerCase ( );
if ( sheet_name == css_sheet_name )
{
the_rules = sheets [ i ].cssRules || sheets [ i ].rules;
found = true;
}
else
{
i++;
done = ( i >= sheets.length );
}
}
if ( found )
{
found = false;
i = 0;
done = ( i >= the_rules.length );
while ( ! ( done || found ) )
{
found = ( the_rules [ i ].selectorText.toLowerCase ( ) ==
selector.toLowerCase ( ) );
if ( found )
{
variable_font_rule = the_rules [ i ];
}
else
{
i++;
done = ( i >= the_rules.length );
}
}
}
if ( variable_font_rule )
{
var cookie = read_cookie ( COOKIE_NAME );
var font_size = DEFAULT_FONT_SIZE;
if ( cookie )
{
font_size = parseInt ( cookie, 10 );
}
variable_font_rule.style.fontSize = ( font_size ) + "px";
create_cookie ( COOKIE_NAME, font_size.toString ( ), 0 );
}
}
}
如果文档包含至少一个 CSS 样式表并提供了两个必需的参数,则 `initialize_font_size` 脚本
- 初始化全局变量 `variable_font_rule`,使其指向控制级联样式表“`css_sheet_name”中声明为“
class='selector'
”的所有元素的字体大小的 CSS 规则(请注意,调用者会为“`css_sheet_name”和“`selector”提供实际值)。 - 如果全局变量 `variable_font_rule` 已成功初始化(即,不是未定义或 `null`),则读取名为 `COOKIE_NAME` 的 cookie 以确定新的字体大小。如果 cookie 不存在,则新字体大小将设置为全局变量 `DEFAULT_FONT_SIZE` 指定的值。
- 通过简单地将 `variable_font_rule` 的 `style.fontSize` 设置为新的字体大小,来将所有受影响的网页元素的字体大小设置为新的字体大小。
- 将新的字体大小写入名为 `COOKIE_NAME` 的 cookie。
包含级联样式表文件名的字符串必须包含扩展名,而包含指定级联样式表中选择器(类名)的字符串必须包含选择器前缀(即,类名的“.”)。
鼠标单击调整大小
我认为向用户表明文本大小调整可用的一种最简单方法是在网页上显示一个视觉线索。为此,我们以 NPR 为指导,使用短语“text size”,后跟不同大小的字母“A”。此外,还包含一个当鼠标悬停在字母上时出现的标题,以使鼠标单击时执行的操作更加明显。
触发鼠标单击文本大小调整的 HTML(在本文顶部图片的右侧显示)封装在一个 `
<div class="textsize">
text size
<a class="small"
href="javascript:void(0);"
onclick="reduce_font_size()"
title="Reduce font size">
A
</a>
<a class="big"
href="javascript:void(0);"
onclick="restore_font_size()"
title="Restore default font size">
A
</a>
<a class="bigger"
href="javascript:void(0);"
onclick="increase_font_size()"
title="Increase font size">
A
</a>
</div>
此字体大小调整实现需要三个函数:`reduce_font_size`、`restore_font_size` 和 `increase_font_size`,它们都在 `control_font_size` 脚本文件中找到。所有这三个函数都需要 `initialize_font_size` 已成功调用,即全局变量 `variable_font_rule` 已成功初始化。此外,这些函数中的每一个都需要 `cookies` 脚本文件中提供的 cookie 支持。
// ************************************************* reduce_font_size
/// <summary>
/// reduces, by one point, the font size of elements that are
/// declared as "class='variable_font'"
function reduce_font_size ( )
{
if ( variable_font_rule )
{
var cookie = read_cookie ( COOKIE_NAME );
var font_size = DEFAULT_FONT_SIZE;
if ( cookie )
{
font_size = parseInt ( cookie, 10 );
}
if ( font_size > MINIMUM_FONT_SIZE )
{
font_size--;
variable_font_rule.style.fontSize = ( font_size ) + "px";
create_cookie ( COOKIE_NAME, font_size.toString ( ), 0 );
}
}
}
// ************************************************ restore_font_size
/// <summary>
/// restores the font size of elements that are declared as
/// "class='variable_font'" to the default font size
function restore_font_size ( )
{
if ( variable_font_rule )
{
var font_size = DEFAULT_FONT_SIZE;
variable_font_rule.style.fontSize = ( font_size ) + "px";
create_cookie ( COOKIE_NAME, font_size.toString ( ), 0 );
}
}
// *********************************************** increase_font_size
/// <summary>
/// increases, by one point, the font size of elements that are
/// declared as "class='variable_font'"
function increase_font_size ( )
{
if ( variable_font_rule )
{
var cookie = read_cookie ( COOKIE_NAME );
var font_size = DEFAULT_FONT_SIZE;
if ( cookie )
{
font_size = parseInt ( cookie, 10 );
}
if ( font_size < MAXIMUM_FONT_SIZE )
{
font_size++;
variable_font_rule.style.fontSize = ( font_size ) + "px";
create_cookie ( COOKIE_NAME, font_size.toString ( ), 0 );
}
}
}
`control_font_size` 脚本中使用的全局常量是
var COOKIE_NAME = "SAVED_VARIABLE_FONT_SIZE";
var DEFAULT_FONT_SIZE = 13;
var MAXIMUM_FONT_SIZE = 24;
var MINIMUM_FONT_SIZE = 8;
cookies 脚本为字体大小脚本提供支持。设置 cookie 以保留用户从网页加载到网页加载的所需字体大小。
// http://www.quirksmode.org/js/cookies.html
// **************************************************** create_cookie
/// <synopsis>
/// create_cookie ( name, value, days );
/// </synopsis>
///
/// <summary>
/// creates a cookie with the specified name, value, and
/// expiration
/// </summary>
///
/// <param name="name">
/// a string containing the name of the cookie. if a cookie
/// with the same name exists, it will be overwritten.
/// </param>
///
/// <param name="value">
/// a string containing the value to be assigned to the
/// cookie
/// </param>
///
/// <param name="days">
/// the cookie expiration, specified in days
/// </param>
///
/// <example>
/// When calling createCookie() you have to give it three
/// three pieces of information: the name and value of the
/// cookie and the number of days it is to remain active.
/// For example, to set a cookie named 'mycookie' to the value
/// 'mycookievalue' and have it active for 7 days, use
///
/// create_cookie ( 'mycookie', 'mycookievalue', 7 );
///
/// If you want the cookie to exist as a session cookie, that is
/// the cookie is trashed when the user closes the browser,
/// set the number of days to 0.
///
/// If you set the number of days to a negative number, the
/// cookie is trashed immediately.
/// <example>
function create_cookie ( name, value, days )
{
var expires = "";
if ( days )
{
var date = new Date ( );
date.setTime ( date.getTime ( ) +
( days * 24 * 60 * 60 * 1000 ) );
expires = "; expires=" + date.toGMTString ( );
}
document.cookie = name + "=" + value + expires + "; path=/";
}
// ****************************************************** read_cookie
/// <synopsis>
/// var cookie = read_cookie ( name );
/// if ( cookie )
/// {
/// // do something with the cookie value
/// }
/// </synopsis>
///
/// <summary>
/// reads the value of a cookie
/// </summary>
///
/// <param name="name">
/// a string containing the name of the cookie to be read
/// </param>
///
/// <returns>
/// if the cookie exists, a string containing the value of
/// the cookie; otherwise, null
/// </returns>
function read_cookie ( name )
{
var cookie = null;
if ( document.cookie.length > 0 )
{
var cookies = document.cookie.split ( ';' );
var name_with_equal = name + "=";
for ( var i = 0; ( i < cookies.length ); i++ )
{
var a_cookie = cookies [ i ];
a_cookie = a_cookie.replace ( /^\s*/, "" );
if ( a_cookie.indexOf ( name_with_equal ) === 0 )
{
cookie = a_cookie.substring ( name_with_equal.length,
a_cookie.length );
break;
}
}
}
return ( cookie );
}
// ***************************************************** erase_cookie
/// <synopsis>
/// erase_cookie ( name );
/// </synopsis>
///
/// <summary>
/// remove the specified cookie
/// </summary>
///
/// <param name="name">
/// a string containing the name of the cookie to be removed
/// </param>
function erase_cookie ( name )
{
create_cookie ( name, "", -1 );
}
我包含以实现动态字体大小调整的 `` 块是:
<script type="text/javascript"
defer="defer"
src="Scripts/control_font_size.js"></script>
<script type="text/javascript"
defer="defer"
src="Scripts/cookies.js"></script>
<script type="text/javascript"
defer="defer"
src="Scripts/next_page.js"></script>
我将 `` 块放在 `