对于偶然发现这篇旧帖子的任何人,我找到了一个我认为完美的解决方案。
您使用 Dave Rupert 编写的这个漂亮的插件,根据自己的喜好配置设置,我为它添加了一个包装器,允许您定义要调整大小的元素。它还存储原始字体大小,因此当您缩放时,文本会受到原始大小的限制,否则会无限缩放。
这是一个 sn-p 和一个 jsfiddle。 JSFiddle
注意:sn-p 仅在 JSFiddle 中调整大小时运行,因此请务必调整屏幕大小。在生产中,它在负载下运行。
var headings = [$('h1'), $('h2'), $('h3')]
$.each(headings, function(index, heading) {
var fontsize = heading.css('font-size');
$(window).on('load resize', function() {
if (heading.parent()[0] &&
heading.parent()[0].scrollWidth > $('.container').innerWidth()) {
heading.fitText(1, {
minFontSize: '10px',
maxFontSize: fontsize
});
}
});
});
/*global jQuery */
/*!
* FitText.js 1.2
*
* Copyright 2011, Dave Rupert http://daverupert.com
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*
* Date: Thu May 05 14:23:00 2011 -0600
*/
$.fn.fitText = function(kompressor, options) {
// Setup options
var compressor = kompressor || 1,
settings = $.extend({
'minFontSize': Number.NEGATIVE_INFINITY,
'maxFontSize': Number.POSITIVE_INFINITY
}, options);
return this.each(function() {
// Store the object
var $this = $(this);
// Resizer() resizes items based on the object width divided by the compressor * 10
var resizer = function() {
$this.css('font-size', Math.max(Math.min($this.width() / (compressor * 10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)));
};
// Call once to set.
resizer();
// Call on resize. Opera debounces their resize by default.
$(window).on('resize.fittext orientationchange.fittext', resizer);
});
};
.container {
width: 80vw;
background: yellow;
}
h1 {
font-size: 5rem;
}
h2 {
font-size: 4rem;
}
h3 {
font-size: 3rem;
}
h4 {
font-size: 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1>GIGANTICFONT</h1>
</div>
<div class="container">
<h2>LargishFont</h2>
</div>
<div class="container">
<h3>Mediumfont</h3>
</div>
<div class="container">
<h4>smallfont</h4>
</div>