我想出了一些類似於Shadow Wizard的工作,它使用oninput
檢測所有形式的輸入(如粘貼,拖放),而不僅僅是鍵盤輸入。它要求關閉textarea的滾動條與下面的CSS:
textarea { overflow: hidden; }
您可能需要設置resize: none;
像火狐4和Chrome瀏覽器。此外,如果沒有空格,Opera的包裝不會中斷,但它不能正確支持word-wrap: word-break;
,所以我不確定你會如何解決此問題。JavaScript的涉及每次改變時間記住textarea的內容,如果文本超出元素的大小,改變回復到以前的值:
var prev = "",
tArea = document.getElementById("limit");
// Need to use onpropertychange event for IE8 and lower
if ("onpropertychange" in tArea && !("oninput" in tArea)) {
tArea.onpropertychange = function() {
// Only run code if value property changes
if (window.event.propertyName == "value")
this.oninput();
}
}
// oninput will fire for all types of input, not just keyboard
tArea.oninput = function() {
// Temporarily remove the onpropertychange event to prevent a stack overflow
var opc = this.onpropertychange;
this.onpropertychange = null;
// Revert value if the text exceeds the size of the box
if (this.scrollHeight > this.offsetHeight) {
this.value = prev;
}
prev = this.value;
if (opc)
this.onpropertychange = opc;
}
工作演示:http://jsfiddle.net/37Jnn/ - 在測試Firefox 4,IE8,Chrome 9,Opera 10.
`onkeyup`對於這類事情來說是一個糟糕的方法。它使得它非常笨重(例如,儘量保持你的手指在鑰匙上)。而且,在Chrome 9中,刪除的字符太多。 – 2011-02-10 09:52:10
@安迪是的,但仍然是最小代碼的工作。 – 2011-02-10 10:07:42