根据文本长度动态更改字体大小

Dynamically change the size of the font size based on text length

本文关键字:字体 动态 文本      更新时间:2023-09-26

>我需要将用户输入的文本显示为固定大小的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>

基于这里最高答案的逻辑,我创建了一个no-jQuery版本

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>

如果按文本长度表示字符数,那么这篇文章指向一个简短的 jquery 片段根据字符数动态更改字体大小

http://jsfiddle.net/jfbrLjt2/

 $('.text').each(function(){
 var el= $(this);
   var textLength = el.html().length;
    if (textLength > 20) {
        el.css('font-size', '0.8em');
    }
});

获取文本字符串的像素大小是一件困难的事情,并且在很大程度上取决于浏览器和用户的设置,因此可能很难提出适用于所有情况的解决方案。

"显示用户输入的文本"是指用户正在文本框中键入内容吗?如果是这样,您可以附加一个按键侦听器,用于检查文本值的长度,然后相应地调整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');
    }
});
<!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>

感谢putvande让我知道一般方法。这是一个改进的版本。

  1. 摆脱回调地狱。
  2. 修复了一些可能导致页面挂起的错误。

相同的网页:

<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;
    }
}

使用很少的Javascript,你可以为CSS类分配字符串的长度,例如:text-length-5text-length-20

然后,根据这些类名专门使用 CSS 来定位不同的font-size

它可能不适用于每种情况,但它对我的案例做得很好,最大长度约为 10-12 个字符。

如果您有 100+ 或 1000+ 个字符,您还可以创建一个接收长度并返回 CSS 类的函数,然后根据这些范围进行样式设置。


.HTML:

<div class="box">ABC</div>
<div class="box">ABCDE</div>

Javascript(jQuery,但同样的想法可以应用于React或vanilla JS(

$(".box").each((i, el)=> {
  const length = $(el).text().length;
  $(el).addClass("text-length-"+length);
})

.CSS:

.box {
  font-size: 16px;
}
.box.text-length-4,
.box.text-length-5,
.box.text-length-6 {
  font-size: 12px;
}

虽然这是一个老问题,并且已经有几个答案(主要是基于更改字体大小直到内容适合(,但我最近不得不对我们的一个项目做类似的事情。

最初我使用了 Joe 答案 (https://stackoverflow.com/a/33492161/587526( 的编辑版本,但后来我开始思考它,并意识到使用简单的"transform: scale(x("操作可以更容易地获得相同的效果。另一个优点是内容缩放以完全适合容器,而调整字体大小可能会导致文本大小欠佳。

计算比例因子的值非常简单,只需将父容器宽度除以子容器宽度即可。如果子内容大于父内容,则结果值将<1.0 - 并将其传递给"transform: scale(("会导致子元素完美地重新调整尺寸。

这是我使用的功能。它使用 jQuery,但也可以轻松更新以直接使用可用的 DOM 函数。

代码大多是不言自明的,但我要指出的是,孩子的"显示"最初被更改为"内联块",因为

等元素不会以其他方式报告它们的宽度。

其他需要注意的事项是,使用"transform: scale(("可能会影响边距。就我而言,我需要确保子元素在父容器内居中,所以我使用了 display: flex:

.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);
};

谁想要一个取决于元素宽度的动态函数(基于 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>

呜��

.div1, .div2, .div3 {
    width: 207px;
    white-space: nowrap;
}

请注意,您只将字体大小设置为跨内部,而不设置为外部div。

你可以试试这个,它对我 100% 有效。

  function resize(){
    const isOverflown = ({ clientWidth, scrollWidth, clientHeight, scrollHeight}) => scrollWidth > clientWidth || scrollHeight > clientHeight
    const resizeText = ({ element, elements, minSize = 10, maxSize = 512, step = 1, unit = 'px' }) => {
      (elements || [element]).forEach(el => {
        let i = minSize
        let overflow = false
            const parent = el.parentNode
        while (!overflow && i < maxSize) {
            el.style.fontSize = `${i}${unit}`
            overflow = isOverflown(parent)
            el.style.lineHeight = ((el.style.fontSize).slice(0, -2))*1.2+"px"
          if (!overflow) i += step
        }
        el.style.fontSize = (`${i - step - 1}${unit}`)
      })
    }
    resizeText({
      elements: document.querySelectorAll('.text'),
      step: 0.5
    })
  }
  
    if (document.readyState === 'complete') {
    resize();
  } else {
    window.onload = resize();
  }
<div id="outer" style="width:200px; height:80px; border:1px solid red;">
    <div class="text">Lorem ipsum</div>
</div>
<div id="outer" style="width:200px; height:80px; border:1px solid red;">
    <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing 
    elit. Integer mollis dui felis, vel vehicula tortor cursus nec.</div>
</div>