jQuery 如何自动更改div内的文本大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6112660/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:24:52  来源:igfitidea点击:

How to automatically change the text size inside a div?

jqueryhtmlcssfont-size

提问by useCase

I have a background image with a div. I want to write some text, but this text should change the font size through the div.

我有一个带有div. 我想写一些文本,但是这个文本应该通过div.

回答by DanielB

I understand your question this way, you would like to fit some text into a given div with a fixed dimension, and if the div is too small to show all the text, the font size should be shrinked until the text fits into the div. If that's the point, here is my solution.

我以这种方式理解您的问题,您希望将一些文本放入具有固定尺寸的给定 div 中,如果 div 太小而无法显示所有文本,则应缩小字体大小,直到文本适合该 div。如果这是重点,这是我的解决方案。

Here is an example with a jQuery implementaion: http://jsfiddle.net/MYSVL/2/

这是一个带有 jQ​​uery 实现的示例:http: //jsfiddle.net/MYSVL/2/

Here is a div

这是一个div

<div id="fitin">
    <div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div>

With a fixed size

有固定尺寸

#fitin {
    width: 300px;
    height: 100px;
    border: 1px solid black;
    overflow: hidden;
    font-size: 1em;
}

This JavaScript will do the job.

这个 JavaScript 将完成这项工作。

$(function() {
    while( $('#fitin div').height() > $('#fitin').height() ) {
        $('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px" );
    }
});

回答by jdhurst

FlowType.js will do just that: resize the font to match the bounding element, be it a div or another element type.

FlowType.js 将做到这一点:调整字体大小以匹配边界元素,无论是 div 还是其他元素类型。

An example of implementing FlowType:

一个实现 FlowType 的例子:

  1. Set up your style

    body {
    font-size: 18px;
    line-height: 26px;
    }
    
  2. Download FlowType from GitHuband include a reference to it in your head element

    flowtype.jQuery.js
    
  3. Call FlowType

    $('body').flowtype();
    
  4. (optional) Update default settings

    $('body').flowtype({
    minimum   : 500,
    maximum   : 1200,
    minFont   : 12,
    maxFont   : 40,
    fontRatio : 30,
    lineRatio : 1.45
    });
    
  1. 设置你的风格

    body {
    font-size: 18px;
    line-height: 26px;
    }
    
  2. 从 GitHub 下载 FlowType并在您的 head 元素中包含对它的引用

    flowtype.jQuery.js
    
  3. 呼叫流程类型

    $('body').flowtype();
    
  4. (可选)更新默认设置

    $('body').flowtype({
    minimum   : 500,
    maximum   : 1200,
    minFont   : 12,
    maxFont   : 40,
    fontRatio : 30,
    lineRatio : 1.45
    });
    

Check out their homepagefor an interactive demo

查看他们的主页以获取交互式演示

回答by Ideogram

The question has been answered since long, but I'd like to add some notes.

这个问题已经回答很久了,但我想添加一些注释。

Since, an extra jQuery plugin has been added to the universe: FlowType.js

此后,一个额外的 jQuery 插件已添加到 Universe:FlowType.js

https://github.com/simplefocus/FlowType.JS

https://github.com/simplefocus/FlowType.JS

I tried my hand at the given solutions and plugins (including FlowType.JS), in the end I wrote my own. I just like to include it here as 'inspiration'. I use a different approach: I calculate the ratio that the size of the text is larger then it's parent. I don't know if it makes sense, but for me it works nicely.

我尝试了给定的解决方案和插件(包括 FlowType.JS),最后我自己写了。我只是想把它包括在这里作为“灵感”。我使用不同的方法:我计算文本大小大于父文本大小的比率。我不知道这是否有意义,但对我来说它很好用。

    /* shrinkText jQuery Plugin  */

(function( $ ){

  $.fn.shrinkText = function() {

    var $_me = this;
    var $_parent = $_me.parent();

    var int_my_width = $_me.width();
    var int_parent_width = $_parent.width();

    if ( int_my_width > int_parent_width ){

      rl_ratio =   int_parent_width / int_my_width;

      var int_my_fontSize = $_me.css("font-size").replace(/[^-\d\.]/g, '');

      int_my_fontSize = Math.floor(int_my_fontSize * rl_ratio);

      $_me.css("font-size", int_my_fontSize + "px");

    }
  };

})( jQuery );

It assumes a inline-element within a block-level element, it shrinks the inline element by recalculating the font-size.

它假定块级元素中有一个行内元素,它通过重新计算字体大小来缩小行内元素。

HTML:

HTML:

<h1 style="white-space:nowrap;">
  <a href="#" >Macrobenthos of the North Sea - Miscellaneous worms</a>
</h1>

JavaScript:

JavaScript:

if( jQuery().shrinkText ){
    $("#title a").shrinkText();
}

回答by Robert Koritnik

I'm not completely sure I understand your question but I think what you're asking is how to fit text in a particular container of predefined size. I'll try to answer this question.

我不完全确定我理解您的问题,但我认为您要问的是如何将文本放入预定义大小的特定容器中。我会试着回答这个问题。

Client side

客户端

When you want to do this on demand on the client you will have to run Javascript. The idea is to:

当您想在客户端上按需执行此操作时,您将必须运行 Javascript。这个想法是:

  1. generate an invisible divand set its style to:

    position: absolute;
    top: 0;
    left: 0;
    width: auto;
    height: auto;
    display: block;
    visibility: hidden;
    font-family: /* as per your original DIV */
    font-size: /* as per your original DIV */
    white-space: /* as per your original DIV */
    
  2. copy your text to it

  3. check whether DIV's width exceeded the size of your original DIV.

  4. adjust font-sizevalue by not simply incrementing/decrementing but rather by calculating width difference between your invisible and original DIV. This will deviate to correct size much faster.

  5. go to step 3.

  1. 生成一个隐形div并将其样式设置为:

    position: absolute;
    top: 0;
    left: 0;
    width: auto;
    height: auto;
    display: block;
    visibility: hidden;
    font-family: /* as per your original DIV */
    font-size: /* as per your original DIV */
    white-space: /* as per your original DIV */
    
  2. 将您的文本复制到它

  3. 检查 DIV 的宽度是否超​​过了原始 DIV 的大小。

  4. font-size通过不是简单地增加/减少而是通过计算不可见和原始 DIV 之间的宽度差异来调整值。这将更快地偏离正确的尺寸。

  5. 转到步骤3

Server side

服务器端

There is no reliable way of setting font size on the server so it will fit your client rendered container. Unfortunately you can only approximate sizes on pretested empirical data.

没有在服务器上设置字体大小的可靠方法,因此它适合您的客户端渲染容器。不幸的是,您只能根据预先测试的经验数据估算大小。

回答by Renzo Ciot

I extend DanielB solution in the case when you have a complex HTML inside the div and you want to maintains ratio between different elements:

如果 div 中有复杂的 HTML 并且想要保持不同元素之间的比例,我会扩展 DanielB 解决方案:

$(function() {
    $(window).on('resize', function() {
        $('#fitin').css('font-size', '1em');
        var count = 0;
        while( count< 30 && $('#fitin').height() > $('#fitin div').height() ) { 
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) + 1) + "px");
            });
            count++;
        } 
        count = 0;
        while( count< 30 && $('#fitin div').height() > $('#fitin').height()-20 ) {
            $('#fitin *').each(function( index ) {
                $(this).css('font-size',(parseInt($(this).css('font-size')) - 1) + "px");
            })
            count++;
        }
    });
    $(window).trigger('resize');  
});

回答by Adacho

I have made better version of @DanielB code, maybe it save someone time :)

我已经制作了更好版本的@DanielB 代码,也许可以节省一些时间:)

(Just add class RESIZABLE to div you want to be changed)

(只需将类 RESIZABLE 添加到要更改的 div 中)

$(document).ready(function() {
    $(window).resize(function() {

        $('.RESIZABLE').each(function(i, obj) {
            $(this).css('font-size', '8em');

            while ($(this).width() > $(this).parent().width()) {
                $(this).css('font-size', (parseInt($(this).css('font-size')) - 1) + "px");
            }
        });






    });
});

回答by Luke Brown

Check out this example here http://codepen.io/LukeXF/pen/yOQWNb, you can use a simple function on page load and page resize to make the magic happen.

在此处查看此示例http://codepen.io/LukeXF/pen/yOQWNb,您可以在页面加载和页面调整大小上使用一个简单的函数来实现奇迹。

function resize() {  
    $('.resize').each(function(i, obj) {
        $(this).css('font-size', '8em');

        while ($(this).width() > $(this).parent().width()) {
            $(this).css('font-size', (parseInt($(this).css('font-size')) - 1) + "px");
        }
    });
}

回答by jantimon

You have to preload the image to get the width and height of the image.

您必须预加载图像以获取图像的宽度和高度。

As soon as you got the dimensions you can "try" different fontsizes:

一旦获得尺寸,您就可以“尝试”不同的字体大小:

$("<img/>").appendTo(document.body).attr('src','myBackground.png').load(function(){
    var width = $(this).width(), height = $(this).height(),
        $div = $("#myDivId"),
        font = 30;

    do{
      font--;
      $div.css('font-size',font);
    }while($div.width()>width || $div.height()>height || font == 0);

    $div.width(width);
    $div.height(height);
});

回答by OBender

Here is a global function with JQuery and HTML5 Data annotations to define the block size take a look:

这是一个带有 JQuery 和 HTML5 数据注释的全局函数来定义块大小,看看:

Don't ask me why I need the table :-) , the width function works best with tables... on Jquery 1.7 .. Getting no width for Divs

不要问我为什么需要表格 :-) ,宽度函数最适合表格...在 Jquery 1.7 上 .. Divs 没有宽度

Usage :

用法 :

<table>
 <tr>
    <td class="caa" data-text-max-width="500" data-text-max-height="80">
       The Text is Here
    </td>
 </tr>
</table>

Function to add:

添加功能:

$(function () {
    var textConsts = {
        MIN_SIZE_OF_A_TEXT: 9
    };

    $('*[data-text-max-width]').each(function () {

        var textMaxWidth = $(this).data("text-max-width");
        var textMaxHeight = $(this).data("text-max-height");
        var minSizeOfaText = $(this).data("text-min-size");

        $(this).css('font-size', '9em');

        if (minSizeOfaText == null || !($(this).hasData("text-min-size")))
            minSizeOfaText = textConsts.MIN_SIZE_OF_A_TEXT;

        if (textMaxWidth == null || !($(this).hasData("text-max-width")))
            textMaxWidth = $(this).parent().width();

        if (textMaxHeight == null || !($(this).hasData("text-max-height")))
            textMaxHeight = $(this).parent().height();

        var curentWidth = $(this).width();
        var curentFontSize = 0;
        var numberOfRounds = 0;
        var currentHeigth = $(this).height();
        curentFontSize = parseInt($(this).css('font-size'));
        var lineHeigth = parseInt($(this).css('line-height'));
        if (currentHeigth > (curentFontSize * lineHeigth)) {
            curentWidth += curentFontSize * lineHeigth;
        }

        while (curentWidth > textMaxWidth || currentHeigth > textMaxHeight) {

            curentFontSize = parseInt($(this).css('font-size'));
            curentFontSize -= 1;

            $(this).css('font-size', curentFontSize + "px");

            curentWidth = $(this).width();
            currentHeigth = $(this).height();

            if (currentHeigth > (curentFontSize * 1.5))
                curentWidth += curentFontSize * 1.5;

            numberOfRounds += 1;

            if (numberOfRounds > 1000)
                break;

            if (curentFontSize <= minSizeOfaText)
                break;
        }

        $(this).css('height', textMaxHeight + "px");
        $(this).css('width', textMaxWidth + "px");
    });

});