带换行符的文字大小

时间:2017-05-31 13:25:43

标签: jquery css text

我有以下函数来计算文本的最大大小:

        function MyFitText(width, height, text)
        {
            var ourText = $('span').css('font-weight', 'bold').text(text);
            var fontSize = 20;
            ourText.css('font-size', fontSize);
            do {
                fontSize = fontSize - 1;
                textHeight = ourText.height();
                textWidth = ourText.width();
                ourText.css('font-size', fontSize);
            } while ((textHeight > height || textWidth > width) && fontSize > 1);

            return fontSize;
        }

它适用于单行文本,但如何计算2行以上的行? Chrome中的调试器说明如下: enter image description here

因此,存在换行符,但它会像它的单行文本一样计算。

MODIFY

我已通过以下方式修改了我的功能(感谢gaetanoM):

        function MyFitText(width, height, text)
        {
            var ourTextArr = [];

            var texts = text.split('\n');
            var fontSize = 20;
            $.each(texts, function (index, value) {
                if (value != '') {
                    var ourText = $('span').css('font-weight', 'bold').text(value);
                    ourText.css('font-size', fontSize);
                    ourTextArr.push(ourText);
                }
            });

            do{
                fontSize = fontSize - 1;
                var textHeight = 0;
                var textWidth = 0;
                $.each(ourTextArr, function(index, value) {
                    textHeight += value.height();
                    if (value.width() > textWidth)
                        textWidth = value.width();
                    value.css('font-size', fontSize);
                });
            }
            while ((textHeight > height || textWidth > width) && fontSize > 1);
            return fontSize;
        }
更改font-size时会更改

value.width(),但value.height()始终保持不变。为什么呢?

1 个答案:

答案 0 :(得分:0)

测量<span>的高度不起作用:内联元素的高度始终为一行高。如果要测量文本块的高度,则需要将其放在块级元素中(即<div>。)

你试图通过调整字体大小来将文本放在预定区域内 - 但是让宽度和高度都漂浮在它们周围,直到它们适合通常不合适(留下一个维度或另一个维度太大) 。相反,将div的宽度设置为预定宽度,然后减小字体大小,直到测量高度低于预定高度:

function MyFitText(width, height, text) {
  var $container = $('#container');
  $container
    .width(width) // <-- set a fixed width
    .html(text.replace(/\n/g, '<br>')) // <-- (so we can measure all together instead of splitting on newlines)
    .css('font-weight', 'bold'); // <-- probably belongs in CSS instead
    
  for (var fontSize = 20; fontSize > 0; fontSize--) {
    $container.css('font-size', fontSize+'px');
    if ($container.height() <= height) {
      break;
    }
  }
  return fontSize;
}

// Test rig so you can play with different values:
$('#test').click(function() {
  var w = $('#w').val();
  var h = $('#h').val();
  var t = $('#t').val();
  var size = MyFitText(w,h,t);
  console.log("Set font-size to "+size+"px");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Desired width: <input id="w" value="200"><br>
Desired height: <input id="h" value="400"><br>
Text: <textarea id="t">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. 

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
</textarea><br>
<button id="test">Test it</button>

<div id="container"></div>