Limit text length based on fitting text inside fixed width and height box

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-14 03:55:40

问题


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/

来源:https://stackoverflow.com/questions/14306083/limit-text-length-based-on-fitting-text-inside-fixed-width-and-height-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!