让网页文字自动适配方框大小

阅读约 2 分钟 html, javascript, fonts

写于 2011 年。此后工具、API 和价格可能已有变化。

我最近在做一个同时面向智能手机和平板的 Web 应用。屏幕尺寸差异太大,于是我选择了一种按比例分配的动态布局,让界面去适应可用空间。比如,我把垂直方向 20% 的空间分给了显示标题的页头区域。内容区域的布局用 jQuery UI.Layout Plug-in 搞定了,效果很好,但到了让文字也按比例缩放这一步,我卡住了。

问题本身很简单:我有一个方框,想在里面用尽可能大的字号显示一段文字,同时既不换行也不被截断。要知道一段带有特定字体属性的文字占多大的矩形区域,唯一的办法就是把它创建出来、加到 DOM 里,然后再量一量。下面这个函数做的就是这件事。

function sizeWithText(text, cssStyles) {
	// create temp element to hold our text
	var e = document.createElement('span');
	e.appendChild(document.createTextNode(text));

	// apply any styles that have been passed in
	// to our element - these can affect the text size
	for (var prop in cssStyles) {
		e.style[prop] = cssStyles[prop];
	}

	// hide our temp element
	e.style['visibility'] = 'hidden';

	// add to DOM in order to have it render
	document.body.appendChild(e);

	// get the bounding rectangle dimensions
	var s = {w: e.offsetWidth, h: e.offsetHeight};

	// remove from DOM
	document.body.removeChild(e);

	return s;
}

cssStyles 参数用来传入你想应用到文字上的其他 CSS 样式属性。比如 font-weight: bold 会让文字变大,我们得确保把它也算进去。

有了这个函数,就可以检查某个字号加上一组样式后,文字能不能放进方框里。我们从字号 1 开始,每次加 1,每一轮都检查一次是否还放得下。一旦放不下,就停止。

function bestFitTextSize(text, css, width, height) {
	var pixel = 1;

	do {
		css['font-size'] = (pixel++) + 'px';
		s = sizeWithText(text, css);
	} while ( (s.w < width) && (s.h < height) )

	return pixel - 2;
}

这是一种暴力而且低效的算法,还有不少可以改进的地方。比如可以从一个合理的字号(像 6px)开始,按常用字号递增,等等。不过对我来说已经够用了,因为我只在应用加载时算一次。

下面这段示例代码演示了怎么使用前面这两个函数。

// box we want to fill with text
var c = document.getElementById('content');

// out text
var text = 'Lorem ipsum dolor sit amet';

// styles
var cssStyles = {
	'font-family': 'Impact',
	'font-style': 'normal',
	'font-weight': 'bolder',
	'letter-spacing': '1px',
	'text-shadow': '3px 3px 3px white'
};

// size the text to fit
function applyBestFitText() {
	// get the pixel size for the font
	var px = bestFitTextSize(text, cssStyles, c.offsetWidth, c.offsetHeight);
	cssStyles['font-size'] = px + 'px';

	// set the text
	c.innerHTML = text;

	// apply our styles
	for (var prop in cssStyles) {
		c.style[prop] = cssStyles[prop];
	}
}

// adjust if the size changes
window.addEventListener('resize', applyBestFitText, false);

// call for first time adjustment
applyBestFitText();

完整示例放在了 gist 上。

继续学习

通过邮件获取新的指南和课程

我发布新的指南、课程或文章时,偶尔会发一封邮件。绝无垃圾邮件,随时可以退订。 邮件内容为英文。

由 Buttondown 发送。我绝不会分享你的邮箱地址。更喜欢订阅源?请使用RSS 订阅源。