使用 css 和 html 根据文本长度动态更改字体大小的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18229230/
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
dynamically changing the size of font size based on text length using css and html
提问by user2613399
I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.
我需要将用户输入的文本显示到固定大小的 div 中。我想要的是自动调整字体大小,以便文本尽可能地填充框。
I'd probably want to start with a maximum font size and while the text is too big to fit the container, shrink the font size until it fits and the font must be displayed as a single line. Is it possible to do this using only css and html.
我可能想从最大字体大小开始,当文本太大而无法容纳容器时,缩小字体大小直到它适合并且字体必须显示为单行。是否可以仅使用 css 和 html 来做到这一点。
回答by putvande
Say you have this:
说你有这个:
<div id="outer" style="width:200px; height:20px; border:1px solid red;">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis dui felis, vel vehicula tortor cursus nec</div>
</div>
Then you can do something like:
然后你可以做这样的事情:
$(document).ready(function () {
resize_to_fit();
});
function resize_to_fit(){
var fontsize = $('div#outer div').css('font-size');
$('div#outer div').css('fontSize', parseFloat(fontsize) - 1);
if($('div#outer div').height() >= $('div#outer').height()){
resize_to_fit();
}
}
Working Sample
工作样本
$(document).ready(function() {
resize_to_fit();
});
function resize_to_fit() {
var fontsize = $('div#outer div').css('font-size');
$('div#outer div').css('fontSize', parseFloat(fontsize) - 1);
if ($('div#outer div').height() >= $('div#outer').height()) {
resize_to_fit();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer" style="width:200px; height:20px; border:1px solid red;">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis dui felis, vel vehicula tortor cursus nec</div>
</div>
回答by cfs
Getting the size in pixels of a string of text is a hard thing to do and depends a lot on the browser and the user's settings, so it will probably be hard to come up with a solution that works in all cases.
获取文本字符串的像素大小是一件困难的事情,并且在很大程度上取决于浏览器和用户的设置,因此可能很难提出适用于所有情况的解决方案。
By "display user entered text" do you mean the user is typing into a textbox? If so, you can attach a keypress listener that checks the length of the value of the text, then adjusts the font-size
accordingly. Here's an example, though you will probably need to change the lengths and font-sizes to meet your needs:
“显示用户输入的文本”是指用户正在输入文本框吗?如果是这样,您可以附加一个按键侦听器来检查文本值的长度,然后相应地调整font-size
。这是一个示例,但您可能需要更改长度和字体大小以满足您的需要:
$('#text').on('keypress', function(e) {
var that = $(this),
textLength = that.val().length
;
if(textLength > 30) {
that.css('font-size', '5px');
} else if(textLength > 20) {
that.css('font-size', '10px');
} else if(textLength > 10) {
that.css('font-size', '15px');
}
});
回答by Akin Hwan
If by text length you mean character count, there is this article which points to a short jquery snippet Change Font Size dynamically based on Character count
如果文本长度是指字符数,则有这篇文章指向一个简短的 jquery 代码片段 Change Font Size dynamic based on Character count
$('.text').each(function(){
var el= $(this);
var textLength = el.html().length;
if (textLength > 20) {
el.css('font-size', '0.8em');
}
});
回答by Anon
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div1{
width: 200px;
height: 200px;
font-size: 32px;
line-height: 1.2em;
}
</style>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(function(){
n = 1;
while(n==1){
n = 0
if ($('#div1 .holder').outerHeight()>$('#div1').outerHeight()){
var fz = parseInt($('#div1').css('font-size'));
$('#div1').css({'font-size' : fz-1});
n = 1
} else {n = 0}
}
});
</script>
</head>
<body>
<div id="div1">
<div class="holder">I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.
I'd probably want to start with a maximum font size and while the text is too big to fit the container, shrink the font size until it fits and the font must be displayed as a single line. Is it possible to do this using only css and html.</div>
</div>
</body>
</html>
回答by SRachamim
Whoever wants a dynamic function that depends on the width of the element (based on putvande answer):
谁想要一个取决于元素宽度的动态函数(基于 putvande 答案):
$(document).ready(function () {
var arrEl = ['div1', 'div2', 'div3'];
resize_to_fit(arrEl);
});
function resize_to_fit(arr){
for (var el in arr) {
var jEl = $('.' + arr[el] + ' span');
var fontsize = jEl.css('font-size');
jEl.css('fontSize', parseFloat(fontsize) - 1);
if (jEl.width() >= $('.' + arr[el]).width()){
resize_to_fit([arr[el]]);
}
}
}
and the HTML:
和 HTML:
<div class="div1">
<span>Lorem Ipsum</span>
</div>
<br/>
<div class="div2">
<span>Lorem Ipsum 2</span>
</div>
<br />
<div class="div3">
<span>Lorem Ipsum 3</span>
</div>
whith CSS:
带有CSS:
.div1, .div2, .div3 {
width: 207px;
white-space: nowrap;
}
Notice you only set font-size to span inside, and not to the outer div.
请注意,您只将 font-size 设置为 span 内部,而不是外部 div。
回答by Joe
Thanks putvande for letting me know the general method. Here is an improved version.
感谢 putvande 让我知道一般方法。这是一个改进的版本。
- Get rid of the callback hell.
- Fixed some bugs may cause page hang.
- 摆脱回调地狱。
- 修复了一些可能导致页面挂起的错误。
Same HTML:
相同的 HTML:
<div id="outer" style="width:200px; height:20px; border:1px solid red;">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mollis dui felis, vel vehicula tortor cursus nec</div>
</div>
Here is the function:
这是函数:
resize_to_fit($('#outer'), $('#outer div'));
function resize_to_fit(outer, inner) {
while(inner.height() > outer.height()) {
var fontsize = parseInt(inner.css('font-size')) - 1;
inner.css('font-size', fontsize);
// some browsers(chrome) the min font return value is 12px
if(fontsize <= 1 || parseInt(inner.css('font-size')) >= fontsize+1)
break;
}
}
回答by ecairol
Using very little Javascript, you can assign a CSS class with the lengthof the string, eg: text-length-5
or text-length-20
使用很少的 Javascript,您可以使用字符串的长度分配一个 CSS 类,例如:text-length-5
或text-length-20
Then use exclusively CSS to target different font-size
according to those class names.
然后font-size
根据这些类名使用专门的 CSS 来定位不同的对象。
It probably won't work for every case, but it did very well for mine, where the max length was about 10-12 chars.
它可能不适用于所有情况,但它对我来说效果很好,最大长度约为 10-12 个字符。
If you have 100+ or 1000+ chars you can also make a function that receives the length and returns a CSS class, then style base on those ranges.
如果您有 100+ 或 1000+ 个字符,您还可以创建一个接收长度并返回 CSS 类的函数,然后根据这些范围设置样式。
HTML:
HTML:
<div class="box">ABC</div>
<div class="box">ABCDE</div>
Javascript (jQuery, but the same idea can be applied to React, or vanilla JS)
Javascript(jQuery,但同样的想法可以应用于 React 或 vanilla JS)
$(".box").each((i, el)=> {
const length = $(el).text().length;
$(el).addClass("text-length-"+length);
})
CSS:
CSS:
.box {
font-size: 16px;
}
.box.text-length-4,
.box.text-length-5,
.box.text-length-6 {
font-size: 12px;
}