我使用下面的代码缩小字体大小,但它只减少一次,我希望每次输入新字符时都减少。
<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>
答案 0 :(得分:0)
你只有一个条件:
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";
}
&#13;
#allocatedVisionBudget {
width: 10%;
height: 93.3px;
background-color: rgba(255,255,255,0);
border: #f00 solid 1px;
font-size: 60px;
color: #7e8081;
padding: 0px;
}
&#13;
Input: <input type="text" value="" id="allocatedVisionBudget" onkeypress="resizetext(event)" onkeydown="resizetext(event)" onkeyup="resizetext(event)">
&#13;
答案 1 :(得分:0)
您需要做的一些事情
当你设置输入元素字体大小时,它应该用px或%etc等包装为字符串......
这是一个例子:
var x = document.getElementById(“allocatedVisionBudget”)。style.fontSize =“60px”;
这是您的代码的demo
HTML:
<input type="text" value="" id="allocatedVisionBudget" onkeydown="resizetext()">
的javascript:
window.resizetext = function() {
var xy = document.getElementById('allocatedVisionBudget').value;
var x = document.getElementById("allocatedVisionBudget").style.fontSize = "60px";
var i = 0;
var y = xy.length;
if (xy.length > 4) {
document.getElementById("allocatedVisionBudget").style.fontSize = (parseInt(x) - 20) + "px";
}
};
CSS:
#allocatedVisionBudget {
width: 100%;
height: 93.3px;
background-color: rgba(255, 255, 255, 0);
font-size: 60px;
color: #7e8081;
padding: 0px;
}