【发布时间】:2023-12-22 04:49:01
【问题描述】:
这是适用于的项目:http://phlak.github.com/jColorClock/。如您所见,现在文本大小只是设置为静态大小。我希望文本始终为窗口宽度的约 90%,但也相应地缩放垂直大小。有没有相对简单的方法来做到这一点?
【问题讨论】:
标签: javascript html css xhtml
这是适用于的项目:http://phlak.github.com/jColorClock/。如您所见,现在文本大小只是设置为静态大小。我希望文本始终为窗口宽度的约 90%,但也相应地缩放垂直大小。有没有相对简单的方法来做到这一点?
【问题讨论】:
标签: javascript html css xhtml
是的!
当窗口用一点点javascript调整大小时,设置你的<body>字体大小。 (为方便起见,我在这里使用了 jQuery:
$( document ).ready( function() {
var $body = $('body'); //Cache this for performance
var setBodyScale = function() {
var scaleSource = $body.width(),
scaleFactor = 0.35,
maxScale = 600,
minScale = 30; //Tweak these values to taste
var fontSize = scaleSource * scaleFactor; //Multiply the width of the body by the scaling factor:
if (fontSize > maxScale) fontSize = maxScale;
if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums
$('body').css('font-size', fontSize + '%');
}
$(window).resize(function(){
setBodyScale();
});
//Fire it when the page first loads:
setBodyScale();
});
因为您的字体大小是在 em 中设置的(完美),所以调整 body 元素的百分比字体大小可以作为通用的“文本缩放”。这将缩放 em 中设置的任何文本 - 如果您想更具体一些,您可以在 <div> 上设置字体大小百分比,它只围绕您想要缩放的元素。
这是一个简单的例子:http://www.spookandpuff.com/examples/dynamicTextSize.html
【讨论】:
var $body = $('body') 行更改为var $zoomElements = $('h1, h2, h3, p'),然后将$('body').css('font-size', fontSize + '%'); 行更改为$zoomElements.css('font-size', fontSize + '%'); - 这会将字体大小应用于您选择的所有元素。不过那会有点奇怪的效果!
在 CSS3 中添加了新的单位,可让您执行此操作。 Sitepoint has a good overview。您肯定想为旧版浏览器提供后备方案,但这是迄今为止最简单的解决方案:
font-size: 35vmin;
【讨论】:
当您不需要那么高的精度(例如,不同设备的几个尺寸)时,另一种选择是使用媒体查询。
【讨论】:
与 Beejamin 的出色答案相同,但稍作调整。
对数学进行了调整,以便您可以设置不会发生缩放的“默认宽度”。这样可以更轻松地使用精确的字体大小设计给定宽度。
现在在 html 元素上设置 font-size,释放 body 元素以在 css 中保存 font-size。
$(function() {
// At this width, no scaling occurs. Above/below will scale appropriately.
var defaultWidth = 1280;
// This controls how fast the font-size scales. If 1, will scale at the same
// rate as the window (i.e. when the window is 50% of the default width, the
// font-size will be scaled 50%). If I want the font to not shrink as rapidly
// when the page gets smaller, I can set this to a smaller number (e.g. at 0.5,
// when the window is 50% of default width, the font-size will be scaled 75%).
var scaleFactor = 0.5;
// choose a maximum and minimum scale factor (e.g. 4 is 400% and 0.5 is 50%)
var maxScale = 4;
var minScale = 0.5;
var $html = $("html");
var setHtmlScale = function() {
var scale = 1 + scaleFactor * ($html.width() - defaultWidth) / defaultWidth;
if (scale > maxScale) {
scale = maxScale;
}
else if (scale < minScale) {
scale = minScale;
}
$html.css('font-size', scale * 100 + '%');
};
$(window).resize(function() {
setHtmlScale();
});
setHtmlScale();
});
【讨论】:
如果你使用 jQuery,你可能想试试FitText。它使您可以轻松地将文本缩放到元素的宽度。
另一个选项是FlowType.JS,其工作方式类似。
【讨论】:
【讨论】: