繁体   English   中英

动态字体调整

[英]Dynamic font resize

该脚本根据文本长度调整文本大小。 一切正常,但删除字符时文本无法调整大小。 缺少了什么? 希望周围有一个脚本大师可以帮助我!

  $('#location').keypress(function() { var textLength = $(this).val().length; if (textLength < 20) { // Do noting } else if (textLength < 40) { $(this).css('font-size', '16px'); } else if (textLength > 40) { $(this).css('font-size', '24px'); } //console.log(textLength); }); 
 #location { font-size: 24px; outline: none; width: 200px; height: 30px; display: table-cell; vertical-align: middle; border: 1px solid #ccc; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="location" placeholder="Placeholder Text" /> 

keypress不会在退格键上触发,因此请立即将其更改为keyup

$('#location').keyup(function() {

    var textLength = $(this).val().length;

    if (textLength < 20) {
      // Do noting 
    } else if (textLength < 40) {
      $(this).css('font-size', '16px');
    } else if (textLength > 40) {
      $(this).css('font-size', '24px');
    }
    //console.log(textLength);
  }); 

这是你想做的吗?

Kepress仅适用于可打印字符。 为了检测退格并删除,请使用keyupkeydown

 $(document).on('keyup keydown','#location',function() { var textLength = $(this).val().replace(/\\s+/g,'').length; // first replace spaces then count console.log("Length without spaces "+textLength); if (textLength < 20) { $(this).css('font-size', '24px'); } else if (textLength < 40) { $(this).css('font-size', '16px'); } else if (textLength > 40) { $(this).css('font-size', '24px'); } //console.log(textLength); }); 
 #location { outline: none; width: 200px; height: 30px; display: table-cell; vertical-align: middle; border: 1px solid #ccc; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="location" placeholder="Placeholder Text" /> 

  1. 按键将不会触发上退格,所以改变它,而不是到KEYUP

  2. 删除else条件并仅在以下情况下使用

     $('#location').keyup(function() { var textLength = $(this).val().length; if (textLength < 40) { $(this).css('font-size', '16px'); } if (textLength > 40) { $(this).css('font-size', '24px'); } //console.log(textLength); }); 

暂无
暂无

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

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