2016-02-05 182 views
0

我正在使用下面的代碼來縮小字體大小,但它只會減少一次,我希望它在每次輸入新字符時都減少。調整文本框的字體大小

<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

@SrinivasR,javascript,不是jquery! – Gavriel

+0

@SrinivasR不,它不是。 'getElementById'只需要一個ID,所以你不會傳遞** hash **標識符。 – George

+0

哦對不起我的壞.....我刪除了我的答案。謝謝@Gavriel和喬治 –

回答

0

你只需要一個條件:

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)">
012:作爲文本長度的函數來計算你需要兩

+0

你可以上傳代碼,以使字體大小計算爲文本長度的函數 –

+0

現在查看我的答案。它有效,但並不完美。問題是,當回調被稱爲onkeydown時,你還不知道這個事件將被應用後的文本是什麼(換句話說,當你看到值是「123」,現在你在一個keydown事件中,您不知道在處理當前事件後文本是否會更短/相同/更長,因爲該鍵可以是「4」,但它可以是退格或刪除,或者只是移位。 – Gavriel

0

的幾件事情要做

  1. 當你設置爲輸入元素字體大小應包裝成字符串像素或百分比等...

    這是例子:

    var x = document.getElementById(「allocatedVisionBudget」)。style.fontSize =「60px」;

  2. 當您使用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; 
} 
+0

它只能工作如果長度大於4,我想要的是每當我輸入一個字符它減少字體大小,並且當刪除字體字體大小增加正常 –