How to automatically change the text size inside a

2019-01-02 23:25发布

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.

9条回答
一夜七次
2楼-- · 2019-01-02 23:58

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

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

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

});
查看更多
Viruses.
3楼-- · 2019-01-03 00:08

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:

  1. generate an invisible div and 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-size value 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.

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.

查看更多
\"骚年 ilove
4楼-- · 2019-01-03 00:09

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);
});
查看更多
Ridiculous、
5楼-- · 2019-01-03 00:12

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:

$(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');  
});
查看更多
成全新的幸福
6楼-- · 2019-01-03 00:12

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.

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");
        }
    });
}
查看更多
爷的心禁止访问
7楼-- · 2019-01-03 00:14

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

An example of implementing FlowType:

  1. Set up your style

    body {
    font-size: 18px;
    line-height: 26px;
    }
    
  2. Download FlowType from GitHub and 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
    });
    

Check out their homepage for an interactive demo

查看更多
登录 后发表回答