私は、キーボード入力だけでなく、oninput
を使用してすべての入力形式(貼り付け、ドラッグ/ドロップなど)を検出するShadow Wizardの取り組みに似たものを思いつきました。これは、次のCSSでテキストエリアのスクロールバーをオフにする必要があります。
textarea { overflow: hidden; }
あなたは、Firefox 4やChromeなどのブラウザ用のresize: none;
を設定することをお勧めします。また、スペースがなければOperaのラッピングは壊れませんが、word-wrap: word-break;
は正しくサポートされていないので、これを回避する方法がわかりません。JavaScriptは、テキストエリアの内容にそれを変更するたびに思い出し伴い、テキスト要素のサイズを超えた場合、変更は以前の値に戻され:http://jsfiddle.net/37Jnn/ - でテスト:デモ作業
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;
}
Firefox 4、IE8、Chrome 9、Opera 10。
'onkeyup'は、この種のことに対しては貧弱なアプローチです。それは非常にclunkyになります(例えば、キーに指を置いてみてください)。また、Chrome 9ではあまりにも多くの文字が削除されています。 –
@Andyはい、それでも、最低限のコードで仕事をしています。 –
十分大きなテキストを入力したとき、最後の記号ではなく最後の文字列の半分(ff 3.6)を切り捨てます。 –