调整文本框的字体大小
我正在使用下面的代码来缩小字体大小,但它只会减少一次,我希望它在每次输入新字符时都减少。调整文本框的字体大小
<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) {
所以只有当你改变lenght 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)">
你可以上传代码,以使字体大小计算为文本长度的函数 –
现在查看我的答案。它有效,但并不完美。问题是,当回调被称为onkeydown时,你还不知道这个事件将被应用后的文本是什么(换句话说,当你看到值是“123”,现在你在一个keydown事件中,您不知道在处理当前事件后文本是否会更短/相同/更长,因为该键可以是“4”,但它可以是退格或删除,或者只是移位。 – Gavriel
的几件事情要做
-
当你设置为输入元素字体大小应包装成字符串像素或百分比等...
这是例子:
var x = document.getElementById(“allocatedVisionBudget”)。style.fontSize =“60px”;
- 当您使用X-20的x是字符串,所以你需要使用parseInt(x)函数
这里是你的代码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;
}
它只能工作如果长度大于4,我想要的是每当我输入一个字符它减少字体大小,并且当删除字体字体大小增加正常 –
@SrinivasR,javascript,不是jquery! – Gavriel
@SrinivasR不,它不是。 'getElementById'只需要一个ID,所以你不会传递** hash **标识符。 – George
哦对不起我的坏.....我删除了我的答案。谢谢@Gavriel和乔治 –