Javascript 如何根据窗口宽度增加字体大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3146395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I increase the font size based on the window width?
提问by Josh Brown
I am creating a web-based app that will be displayed on television and other large monitors. I am wanting a quick and easy way to increase the font size to fit the window size. The text is dynamic.
我正在创建一个基于 Web 的应用程序,它将显示在电视和其他大型显示器上。我想要一种快速简便的方法来增加字体大小以适应窗口大小。文字是动态的。
Any help is greatly appreciated. ;)
任何帮助是极大的赞赏。;)
回答by bochgoch
If you're interested in / able to use CSS3then there is a pure CSS solution - media queries>> http://www.w3.org/TR/css3-mediaqueries/
如果您对/能够使用CSS3感兴趣,那么有一个纯 CSS 解决方案 -媒体查询>> http://www.w3.org/TR/css3-mediaqueries/
So for example, the CSS:
例如,CSS:
@media screen and (min-device-width: 800px) { ... }
...allows you to specify different styles for the page when displayed on a 800px screen or greater. Obviously you can vary this as you like - powerful stuff
...允许您在 800 像素或更大的屏幕上显示时为页面指定不同的样式。显然你可以随心所欲地改变它 - 强大的东西
You may also want to consider the prewritten javascript at the end of this link ... http://www.themaninblue.com/experiment/ResolutionLayout/#
您可能还想考虑在此链接末尾预先编写的 javascript ... http://www.themaninblue.com/experiment/ResolutionLayout/#
回答by Ben Hull
OK - for starters, you should use Ems for as many measurements as you can in your UI. At the very least, size all of your text elements with Ems (rather than pixels or %'s). If possible, setting the width of layout blocks in Ems will help the app scale in proportion, too. If you can set all your dimensions in Ems, your entire app will be visually scalable.
好的 - 首先,您应该在 UI 中使用 Ems 进行尽可能多的测量。至少,使用 Ems(而不是像素或 %)来调整所有文本元素的大小。如果可能,在 Ems 中设置布局块的宽度也有助于应用按比例缩放。如果您可以在 Ems 中设置所有尺寸,您的整个应用程序将在视觉上具有可扩展性。
The key to Ems is that they're sized relative to the font size of their parent element - which means you can adjust the size of all the text in proportion, by adjusting the font-size of the body element (since everything is relative to the body).
Ems 的关键是它们的大小是相对于其父元素的字体大小 - 这意味着您可以通过调整 body 元素的字体大小来按比例调整所有文本的大小(因为一切都相对于身体)。
The last step is to use a piece of javascript to detect the width of the viewport, and set the font-size of the body accordingly. Depending on how fine-grained you want to control the scale, you can either use classes on the body element to set up a set of pre-defined values, or directly manipulate the font-size itself. I'd tend to use pre-determined sizes if possible to make testing easier.
最后一步是使用一段javascript来检测视口的宽度,并相应地设置正文的字体大小。根据您想要控制比例的细粒度,您可以使用 body 元素上的类来设置一组预定义的值,或者直接操作字体大小本身。如果可能的话,我倾向于使用预先确定的尺寸以使测试更容易。
I'd use a javascript library to make the detection of the viewport width easier - it's notoriously different in different browsers. With jQuery, the code could look like:
我会使用一个 javascript 库来更容易地检测视口宽度 - 它在不同的浏览器中是众所周知的不同。使用 jQuery,代码可能如下所示:
$(function(){
var viewPortWidth = $(window).width();
if (viewPortWidth > 1900) {$('body').addClass('extraWide')}
else if (viewPortWidth > 1400) {$('body').addClass('wide')}
else if (viewPortWidth > 1000) {$('body').addClass('standard')}
else if (viewPortWidth > 700) {$('body').addClass('narrow')}
else {$('body').addClass('extraNarrow')}
});
And the CSS:
和 CSS:
<style type="text/css">
body {font-size:62.5%;} /* Set the size of 1em to 10px in all browsers */
body.extraWide {font-size:85%;}
body.wide {font-size:75%;}
body.narrow {font-size:50%;}
body.extraNarrow {font-size:40%;}
</style>
Those values can be tweaked however you like, of course, and you can set up as many divisions as you want. This is very much a quick-and-dirty solution, but should do the trick.
当然,您可以随意调整这些值,并且您可以根据需要设置任意数量的分区。这是一个非常快速和肮脏的解决方案,但应该可以解决问题。
A note- the javascript code shown will only set the scale once when the page is loaded - it won't adjust it when you change the size of your window. That's a possible addition, but there are bigger considerations before heading down that track. Personally, I'd even think about setting the scale value in a cookie, to keep the user's experience consistent throughout their session, rather than rescaling on every page load.
注意- 显示的 javascript 代码只会在页面加载时设置一次比例 - 当您更改窗口大小时,它不会调整它。这是一个可能的补充,但在沿着这条轨道前进之前还有更大的考虑。就个人而言,我什至会考虑在 cookie 中设置缩放值,以保持用户在整个会话期间的体验一致,而不是在每个页面加载时重新缩放。
回答by David
A better version (for me) of the solution provided by japanFour:
japanFour 提供的解决方案的一个更好的版本(对我来说):
$(document).ready(scaleFont);
$(window).resize(scaleFont);
function scaleFont() {
var viewPortWidth = $(window).width();
if (viewPortWidth >= 1900) {$('body').attr('class','extraWide');}
else if (viewPortWidth >= 1400) {$('body').attr('class','wide');}
else if (viewPortWidth >= 1000) {$('body').attr('class','');}
else if (viewPortWidth >= 700) {$('body').attr('class','narrow');}
else {$('body').attr('class','extraNarrow');}
}
So it resizes only if window is resized (avoiding setTimout), and you give bodyonly the exact class it needs
因此,只有在调整窗口大小(避免setTimout)时它才会调整大小,并且您body只提供它需要的确切类
回答by Daan
I know this in quite an old question, but I will be answering anyways due to this being a question that could be searched upon a lot.
我在一个很老的问题中知道这一点,但无论如何我都会回答,因为这是一个可以搜索很多的问题。
There is actually another approach other than Media Queries which is also pure CSS:
除了媒体查询之外,实际上还有另一种方法,它也是纯 CSS:
Viewport units:vw, vh, vmin, vmax.
视口单位:vw、vh、vmin、vmax。
These are length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).
这些长度单位代表视口宽度 (vw)、高度 (vh)、两者中的较小者 (vmin) 或两者中的较大者 (vmax) 的 1% 的视口大小。
So for example you could use:
例如,您可以使用:
CSS:
CSS:
body {
font-size:5vmin;
}
This sets the font-size of the entire document to 5% of the smallest viewport size (the width or the height). So for instance on an iPad (1024 x 768 px) the font-sizewill be 38,4 px(5% of 768 px because this is the smallest size of either viewport sizes).
这会将整个文档的字体大小设置为最小视口大小(宽度或高度)的 5%。因此,例如在 iPad (1024 x 768 px) 上,font-size它将是38,4 px (768 px 的 5%,因为这是任一视口尺寸的最小尺寸)。
Browser compatibility:https://caniuse.com/#feat=viewport-units
浏览器兼容性:https : //caniuse.com/#feat=viewport-units
回答by ErikAGriffin
Is there anything wrong with the following code? While I agree media queries are very useful, I wanted to continuously scale the font-size of certain elements of my page as the window either grew or shrunk. This code seems much simpler than the other jquery solutions of establishing class constants based on viewport pixel width:
下面的代码有什么问题吗?虽然我同意媒体查询非常有用,但我想随着窗口的增长或缩小不断缩放页面某些元素的字体大小。这段代码看起来比其他基于视口像素宽度建立类常量的jquery解决方案简单得多:
$(document).ready(function() {
var setFontSize = function() {
var viewportWidth = $(window).width();
var fontSize = Math.sqrt(viewportWidth/250);
$('.myElement').css('font-size',fontSize+'em');
};
$(window).resize(function() {
setFontSize();
});
setFontSize();
});
回答by user2286309
Here would be my approach (with removing actual classes + Drupal 7 jQuery):
这是我的方法(删除实际类+ Drupal 7 jQuery):
(function ($) {
$(document).ready(function() {
var bodyClassArr = new Array('extraWide', 'wide', 'normal', 'narrow', 'extraNarrow', 'mobile');
function setBodyClass(){
// remove previous classes
for(x in bodyClassArr){
if($('body').hasClass(bodyClassArr[x])){ $('body').removeClass(bodyClassArr[x]); }
}
var viewPortWidth = $(window).width();
if (viewPortWidth > 1900) { $('body').addClass('extraWide'); }
else if (viewPortWidth > 1400) { $('body').addClass('wide'); }
else if (viewPortWidth > 1000) { $('body').addClass('normal'); }
else if (viewPortWidth > 700) { $('body').addClass('narrow'); }
else if (viewPortWidth < 700) { $('body').addClass('mobile'); }
else { $('body').addClass('normal'); }
};
setBodyClass();
$(window).resize(function() { setBodyClass(); });
}); // jquery end
}(jQuery));
回答by Kris Hollenbeck
Beejamin's answer worked as expected, I added a set timeout so it would scale in real time. It doesn't reverse scale though.
Beejamin 的回答按预期工作,我添加了一个设置超时,以便它可以实时扩展。虽然它不会反转比例。
$(document).ready(function() {scaleFont();});
function scaleFont() {
var viewPortWidth = $(window).width();
if (viewPortWidth > 1900) {$('body').addClass('extraWide')}
else if (viewPortWidth > 1400) {$('body').addClass('wide')}
else if (viewPortWidth > 1000) {$('body').addClass('standard')}
else if (viewPortWidth > 700) {$('body').addClass('narrow')}
else {$('body').addClass('extraNarrow')}
setTimeout(scaleFont, 100);
}
EDIT: SOLVED REVERSE EFFECT
编辑:解决反向效应
$(document).ready(function() {scaleFont();});
function scaleFont() {
var viewPortWidth = $(window).width();
if (viewPortWidth >= 1900) {$('body').addClass('extraWide').removeClass('wide, standard, narrow, extraNarrow')}
else if (viewPortWidth >= 1400) {$('body').addClass('wide').removeClass('extraWide, standard, narrow, extraNarrow')}
else if (viewPortWidth >= 1000) {$('body').addClass('standard').removeClass('extraWide, wide, narrow, extraNarrow')}
else if (viewPortWidth >= 700) {$('body').addClass('narrow').removeClass('extraWide, standard, wide, extraNarrow')}
else {$('body').addClass('extraNarrow').removeClass('extraWide, standard, wide, narrow')}
setTimeout(scaleFont, 100);
}
回答by william malo
Heres a simpler and no-jquery solution:
这是一个更简单且无jquery的解决方案:
onresize=onload=function(){document.body.style.fontSize=window.innerWidth+"px"}

