根据jquery中的字符计算字体大小

时间:2017-07-19 05:22:53

标签: javascript jquery asp.net-mvc

我正在尝试创建方法,该方法将读取文本框中的所有字符并返回字体大小值。

我的功能不正常。以下是我的代码

self.preferredContentSize = CGSize(width: 280, height: minimumSize.height)

它不会返回任何错误,但它不起作用。

2 个答案:

答案 0 :(得分:1)

您可以使用解决方案https://jsfiddle.net/5bdLomyp/2/

var sizeInput = function(input) {
    return shrinkToFill(input, 48, '', 'Impact');
}

var shrinkToFill = function(input, fontSize, fontWeight, fontFamily) {
    var font = fontWeight + ' ' + fontSize + 'px ' + fontFamily;
    var $input = $(input);
    var maxWidth = $input.width() - 50;

    // we're only concerned with the largest line of text.
    var longestLine = $input.val().split('\n').sort(function (a, b) {
        return measureText(a, font).width - measureText(b, font).width;
    }).pop();

    var textWidth = measureText(longestLine, font).width;
    if (textWidth >= maxWidth) {
        // if it's too big, calculate a new font size
        // the extra .9 here makes up for some over-measures
        fontSize = fontSize * maxWidth / textWidth * 0.9;
        font = fontWeight + ' ' + fontSize + 'px ' + fontFamily;
        // and set the style on the input
       
    }
    else {
        font = fontWeight + ' ' + fontSize + 'px ' + fontFamily;
        // and set the style on the input        
    }
    $input.css({
        'font-size': fontSize
    });
    return fontSize;
}
var measureText = function (str, font) {
    str = str.replace(/ /g, ' ');
    var id = 'text-width-tester';
    var $tag = $('#' + id);
    if (!$tag.length) {
        $tag = $('<span id="' + id + '" style="display:none;font:' + font + ';">' + str + '</span>');
        $('body').append($tag);
    } else {
        $tag.css({
            font: font
        }).html(str);
    }
    return {
        width: $tag.width(),
        height: $tag.height()
    };
};

var topText = $('#topText');
var bottomText = $('#bottomText');

$('#topText, #bottomText').keyup(function(){
	 var topFontSize = sizeInput(topText);
   var bottomFontSize = sizeInput(bottomText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="topText" class="hide text-tool top-text" type="text" placeholder="Top Text" />
<input id="bottomText" class="hide text-tool bottom-text" type="text" placeholder="Bottom Text" />

我想这就是你要找的东西。

我没有在HTML中使用 onkeyup onchange ,而是使用了 jQuery keyup 功能。

答案 1 :(得分:0)

以下是答案:

function getFontSize(targetInput) {
        var input = $("<input>").css({ "width": "570px", "height": "52px", "text-align": "center", "font-size": "48px" })
        .val($(targetInput).val());
        var topFontSize = sizeInput(input);
        return topFontSize;
    }
相关问题