我需要将用户输入的文本显示在固定大小的 div 中。我的目标是自动调整字体大小,使文本尽可能填充整个盒子。
我可能希望从最大字体大小开始,而当文本太大无法适应容器时,缩小字体大小,直到它适合并且字体必须显示为一行。
我可能希望从最大字体大小开始,而当文本太大无法适应容器时,缩小字体大小,直到它适合并且字体必须显示为一行。
假设有以下代码:
<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>
然后你可以像这样做:
$(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();
}
}
工作示例
$(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>
const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');
function resize_to_fit() {
let fontSize = window.getComputedStyle(output).fontSize;
output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
if(output.clientHeight >= outputContainer.clientHeight){
resize_to_fit();
}
}
function processInput() {
output.innerHTML =this.value;
output.style.fontSize = '100px'; // Default font size
resize_to_fit();
}
input.addEventListener('input', processInput);
<input type="text" placeholder="Add text input here" style="margin: 10px; width:50%;">
<div id="outer" class="container"
style="width:80%; height:100px; border:2px solid red; font-size:20px;">
<div class="output" style="word-break: break-all; word-wrap: break-word;">
</div>
</div>
无需迭代字体大小。只需计算文本的当前大小和容器的大小,然后应用缩放即可。
const text_el = document.querySelector("#text");
const container_el = document.querySelector("#container");
text_el.addEventListener("input", function(e) {
container_el.children[0].textContent = this.value;
resize2fit(container_el)
});
function resize2fit(el) {
if (!el.parentElement) return;
el.style.setProperty("--font-size", "1em");
const {width: max_width, height: max_height} = el.getBoundingClientRect();
const {width, height} = el.children[0].getBoundingClientRect();
el.style.setProperty("--font-size", Math.min(max_width/width, max_height/height)+"em");
}
window.addEventListener("resize", function(e) {
resize2fit(container_el);
});
resize2fit(container_el);
#container {
width: 100%;
height: 100px;
font-size: var(--font-size, 1em);
white-space: nowrap;
border: 1px solid blue;
}
#container > * {
display: inline-block;
}
<input id="text" value="lorem ipsum" />
<div id="container">
<span>lorem ipsum</span>
</div>
em
单位以保持比例 :) - Florent Descroix $('.text').each(function(){
var el= $(this);
var textLength = el.html().length;
if (textLength > 20) {
el.css('font-size', '0.8em');
}
});
.parent-container {
display: flex;
flex-direction: column;
align-items: center;
}
function resizeToFit(parent, child) {
let $parent = jQuery(parent);
let $child = jQuery(child);
// Temporarily redefine child's display so we
// can obtain the real width
let $display = $child.css('display');
$child.css('display', 'inline-block');
// Remove any existing inline transform
$child.css('transform', '');
// Calculate the scale factor
let factor = $parent.width() / $child.width();
if (factor < 1.0) {
let scale = 'scale(' + factor + ')';
$child.css({
'-webkit-transform' : scale,
'-moz-transform' : scale,
'-ms-transform' : scale,
'-o-transform' : scale,
'transform' : scale
});
}
// Restore the original display value
$child.css('display', $display);
};
获取一段文本的像素大小是一件比较困难的事情,它取决于浏览器和用户的设置,因此很难找到适用于所有情况的解决方案。
如果您所说的“显示用户输入的文本”是指用户在文本框中输入,那么您可以附加一个按键监听器来检查文本值的长度,然后相应地调整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');
}
});
感谢putvande让我知道了一般方法。 这是一个改进的版本。
相同的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>
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;
}
}
func().next().then().etc()..
或者非常嵌套的匿名函数传递... 对吧? - Canistext-length-5
或text-length-20
。font-size
。HTML:
<div class="box">ABC</div>
<div class="box">ABCDE</div>
Javascript(jQuery,但相同的思路也适用于React或原生JS)
$(".box").each((i, el)=> {
const length = $(el).text().length;
$(el).addClass("text-length-"+length);
})
.box {
font-size: 16px;
}
.box.text-length-4,
.box.text-length-5,
.box.text-length-6 {
font-size: 12px;
}
<!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>
while(true)
和 break
。 - reformed谁想要一个依赖于元素宽度的动态函数(基于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]]);
}
}
}
以及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>
使用CSS:
.div1, .div2, .div3 {
width: 207px;
white-space: nowrap;
}
注意你只将字体大小设置为内部的span,而没有设置外部div的大小。