Limit text length based on fitting text inside fix

2019-07-21 03:35发布

I am writting script which limits entered text inside by checking if text fits inside div box which height & width is fixed if not tries to lower font size and then again checks then reached minimum font size it limits text inside textarea. I have accomplished this but it sometimes reaches limit with over height and it do not allow overwrite text then selected.

Here is my script:

function onEdit(e) {
    var notebox_tmp = $(".notebox_tmp");
    var maxHeight = 120;
    var minFontSize = 25;

    notebox_tmp.css("font-size","50px");
    notebox_tmp.text($(this).val());
    var currentHeight = notebox_tmp.height();
    var currentFontSize = parseInt(notebox_tmp.css("font-size"),10);
    while (currentHeight > maxHeight && currentFontSize > minFontSize) {
        notebox_tmp.css("font-size", currentFontSize);
        currentFontSize -= 0.25;
        currentHeight = notebox_tmp.height();
    }
    if (currentFontSize <= minFontSize) { 
      e.preventDefault();
    }
};

$("textarea").keypress(onEdit);

Here is my current script demo: http://jsfiddle.net/6pfCM/9/

0条回答
登录 后发表回答