对于 Google-Chrome,oninput 就足够了(在 Windows 722.0.1229.94 m 版本上进行测试)。
对于 IE9,oninput 将捕捉除了通过上下文菜单和后退空间切割之外的所有内容。
对于 IE8,除了 oninput 之外,还需要 onproperty 修改来捕捉粘贴。
对于 IE9 + 8,onkeyup 需要捕捉回退空间。
对于 IE9 + 8,onmousemove 是我发现的唯一通过上下文菜单捕捉切割的方法
没有在 Firefox 上测试过。
var isIE = /*@cc_on!@*/false; // Note: This line breaks closure compiler...
function SuperDuperFunction() {
// DoSomething
}
function SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally() {
if(isIE) // For Chrome, oninput works as expected
SuperDuperFunction();
}
<textarea id="taSource"
class="taSplitted"
rows="4"
cols="50"
oninput="SuperDuperFunction();"
onpropertychange="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();"
onmousemove="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();"
onkeyup="SuperDuperFunctionBecauseMicrosoftMakesIEsuckIntentionally();">
Test
</textarea>
编辑: 看起来即使上面的解决方案也不是完美的,正如在评论中正确指出的那样: 文本区域中 addEventListener属性的存在意味着你使用的是一个理智的浏览器; 同样地,attachEvent属性的存在意味着 IE。如果您希望您的代码真正无懈可击,那么您应该考虑更改它。有关指针,请参见 Tim Down 的评论。
// Impede que o comentário tenha mais de num_max caracteres
var internalChange= 0; // important, prevent reenter
function limit_char(max)
{
if (internalChange == 1)
{
internalChange= 0;
return;
}
internalChange= 1;
// <form> and <textarea> are the ID's of your form and textarea objects
<form>.<textarea>.value= <form>.<textarea>.value.substring(0,max);
}