简体   繁体   English

Javascript将宽度和高度转换为font-size

[英]Javascript convert width and height to font-size

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 convert specific dimensions (width/height) to a font-size ? 我想知道是否可以计算特定尺寸(宽度/高度)并将其转换为字体大小?

For example, I have : 例如,我有:

var textWidth = 150;
var textHeight = 30;

And I would like to get a font-size from these dimensions (pixels)? 我想从这些尺寸(像素)获得字体大小?

EDIT : Thanks dystroy, I finally managed to resolve this issue with your help. 编辑:谢谢破坏,我终于设法在你的帮助下解决了这个问题。 I used the function posted here and after that, it was not very complicated : 我使用了这里发布的功能,之后,它并不是很复杂:

$(function(){

            $( "#height, #width" ).keyup(function(){

                var varHeight = $( "#height" ).val();
                var varWidth = $( "#width" ).val();

                if(  varHeight != "" && varWidth != "" ){

                    $( "#text_container" ).css( "width", varWidth );    
                    $( "#text_container" ).css( "height", varHeight );

                    $( "#text_container" ).textfill({ maxFontPixels: 500 });

                    var getFontsize = $( "#text_container > span" ).css( "font-size" );
                    var fontSize = parseInt( getFontsize.slice(0, -2) );

                    $( "#fontsize" ).val( fontSize );

                }

            });

        });

Thanks again. 再次感谢。

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/ 我为你所理解的问题制作了一个小界面:输入一些文本的最大宽度和最大高度,它会自动计算字体的大小以适应文本: http//jsfiddle.net/kPZ3E/

HTML : HTML:

Max width : <input id=width value=200> px
<br>Max height : <input id=height value=20> px
<br><br>
<table border=1><tr><td id=txtcell nowrap><span id=txt style=>Some sample text.</span></td></tr></table>
<br>Font Size : <span id=mes></span>​

JS : 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. 注意:小提琴中的超时仅用于显示动画的缩小过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM