Javascript convert width and height to font-size

后端 未结 1 1392
余生分开走
余生分开走 2021-01-16 03:12

I\'m not sure if this question has already been asked and answered but I haven\'t found any relevant result.

I would like to know if it\'s possible to calculate and

1条回答
  •  無奈伤痛
    2021-01-16 03:48

    I've made a small interface for what I understand is your question : you input the max width and max height for some text and it automatically computes the size of the font to adapt the text : http://jsfiddle.net/kPZ3E/

    HTML :

    Max width :  px
    
    Max height : px

    Some sample text.

    Font Size :

    JS :

    var fontSize = 100;
    var reduce = function() {
        $('#txt').css('font-size', fontSize);
        $('#mes').html(fontSize);
        if ($('#txt').width()>$('#width').val() || $('#txt').height()>$('#height').val()) {
           fontSize -= 1;
           reduce();
        }
    };
    reduce();
    $('#width, #height').change(function(){fontSize = 100;reduce()});
    

    Note : the timeout in the fiddle is only here to show the reduction process with an animation.

    0 讨论(0)
提交回复
热议问题