调整文本框的字体大小(resize the font size of the text box)
我使用下面的代码缩小字体大小,但它只减少一次,我希望它每次输入一个新字符时减少。
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()"> <style> #allocatedVisionBudget { width: 10%; height: 93.3px; background-color: rgba(255,255,255,0); border: none; font-size: 60px; color: #7e8081; padding: 0px; } </style> <script> function resizetext(){ var xy = document.getElementById('allocatedVisionBudget').value; var x = document.getElementById("allocatedVisionBudget").style.fontSize=60; //x; xy; var i=0; var y=xy.length; if(xy.length > 4) { document.getElementById("allocatedVisionBudget").style.fontSize=x-20; } } </script>I am using the below code to shrink the font size, but it will reduce only once, I want it to reduce every time when i enter a new character.
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()"> <style> #allocatedVisionBudget { width: 10%; height: 93.3px; background-color: rgba(255,255,255,0); border: none; font-size: 60px; color: #7e8081; padding: 0px; } </style> <script> function resizetext(){ var xy = document.getElementById('allocatedVisionBudget').value; var x = document.getElementById("allocatedVisionBudget").style.fontSize=60; //x; xy; var i=0; var y=xy.length; if(xy.length > 4) { document.getElementById("allocatedVisionBudget").style.fontSize=x-20; } } </script>最满意答案
你只有一个条件:
if(xy.length > 4) {因此,只有在将长度从4更改为5或从5更改为4时才会调整大小。要么添加更多条件,要么更好地将fontSize计算为文本长度的函数:
document.getElementById("allocatedVisionBudget").style.fontSize=f(xy);function resizetext(e){ var xy = document.getElementById('allocatedVisionBudget').value; var l=xy.length; var f = Math.ceil(80/xy.length) || 60; console.log(e, xy, l, f); document.getElementById("allocatedVisionBudget").style.fontSize=f + "px"; }#allocatedVisionBudget { width: 10%; height: 93.3px; background-color: rgba(255,255,255,0); border: #f00 solid 1px; font-size: 60px; color: #7e8081; padding: 0px; }Input: <input type="text" value="" id="allocatedVisionBudget" onkeypress="resizetext(event)" onkeydown="resizetext(event)" onkeyup="resizetext(event)">You only have one condition:
if(xy.length > 4) {so it only resizes when you change the lenght from 4 to 5 or from 5 to 4. Either add more conditions, or better make the fontSize calculated as a function of the text length:
document.getElementById("allocatedVisionBudget").style.fontSize=f(xy);function resizetext(e){ var xy = document.getElementById('allocatedVisionBudget').value; var l=xy.length; var f = Math.ceil(80/xy.length) || 60; console.log(e, xy, l, f); document.getElementById("allocatedVisionBudget").style.fontSize=f + "px"; }#allocatedVisionBudget { width: 10%; height: 93.3px; background-color: rgba(255,255,255,0); border: #f00 solid 1px; font-size: 60px; color: #7e8081; padding: 0px; }Input: <input type="text" value="" id="allocatedVisionBudget" onkeypress="resizetext(event)" onkeydown="resizetext(event)" onkeyup="resizetext(event)">
更多推荐
发布评论