2013-08-24 38 views
0

什麼是跨瀏覽器如何設置textarea中字符的最大數量,使用純Javascript? maxlength不適用於Opera和IE9及以下版本的textareas(儘管它適用於所有主流瀏覽器的輸入)。<textarea>字符數限制

達到字符限制後,textarea不應允許輸入更多字符。使用Ctrl + V或右鍵單擊上下文菜單粘貼的文本應該在字符限制處切斷。這意味着僅使用onkey___事件的解決方案是不夠的。

+0

[釷不同附在可能回答你的問題](http://stackoverflow.com/questions/451491/what-is-the-best-way-to-emulate-an-html-input-maxlength-attribute-on-an-html-t ) – aldanux

回答

2

生成功能將截取該或阻止你的條件下事件,然後將它們添加幾個不同的聽衆對所有你感興趣的事件。

function snip(len) { 
    return function (e) {e.target.value = e.target.value.slice(0, len);}; 
} 
function prevent(len) { 
    return function() { 
     if (e.target.value.length >= len) { 
      e.preventDefault(); 
      return false; 
     } 
    }; 
} 

var len = 5; // choose your length however you want 

var textarea = document.getElementById('texta'), // get the node 
    trunc = snip(len), 
    prev1 = prevent(len), 
    prev2 = prevent(len - 1); 

textarea.addEventListener('change' , trunc, true); 
textarea.addEventListener('input' , trunc, true); 
textarea.addEventListener('keydown' , prev2, true); 
textarea.addEventListener('keypress', prev2, true); 
textarea.addEventListener('keyup' , prev1, true); 
textarea.addEventListener('paste' , trunc, true); 

事件可能需要在IE

DEMO

+0

我還會指出這些因爲它們不會導致無限循環,因爲設置'value = value'不會觸發更改/輸入事件,但如果您正在進行其他更改,那麼請小心。 –

+0

好的答案!但是,這會在最後擦除文本,而不是在達到最大長度時阻止輸入。而不是鼓搗它的工作,我會用'maxlength'去。誰需要Opera和IE9支持? :P –