Textarea onchange检测

tee*_*ink 128 javascript

如何使用javascript检测textarea上的更改事件?
我正在尝试检测您输入的剩余字符数.

我尝试使用onchange事件,但这似乎只在焦点出现时启动.

Vic*_*ani 113

这是2012年,后PC时代就在这里,我们仍然要为这个基本的东西而奋斗.这应该很简单.

在梦想实现之前,这是跨浏览器的最佳方式:使用inputonpropertychange事件的组合,如下所示:

var area = container.querySelector('textarea');
if (area.addEventListener) {
  area.addEventListener('input', function() {
    // event handling code for sane browsers
  }, false);
} else if (area.attachEvent) {
  area.attachEvent('onpropertychange', function() {
    // IE-specific event handling code
  });
}
Run Code Online (Sandbox Code Playgroud)

input活动负责IE9 +,FF,Chrome,Opera和Safari,并onpropertychange负责IE8(它也适用于IE6和7,但有一些错误).

使用的优点input,并onpropertychange为他们不火不必要的(当按下喜欢CtrlShift键); 因此,如果您希望在textarea内容发生变化时运行相对昂贵的操作,那么这就是要走的路.

现在,IE一如既往地做了一个半支持的工作:当从textarea 中删除字符时,IE中既input不会onpropertychange触发也不会触发.因此,如果您需要处理IE中字符的删除,请使用(而不是使用/ ,因为即使用户按下并按住键,它们也只会触发一次).keypresskeyupkeydown

资料来源:http://www.alistapart.com/articles/expanding-text-areas-made-elegant/

编辑:似乎上述解决方案并不完美,正如评论中正确指出的那样:addEventListenertextarea上的属性的存在并不意味着你正在使用一个理智的浏览器; 同样,attachEvent财产的存在并不意味着IE.如果您希望您的代码真的不透气,那么您应该考虑改变它.请参阅Tim Down的评论指针.

  • @StefanSteiger,这就是为什么我的回答建议也使用“keypress”事件来处理 IE9 中的这种情况(也可能是更高版本)。 (2认同)

Jos*_*ola 95

您将需要使用onkeyup onchange为此.onchange将阻止上下文菜单粘贴,并且每次按键都会触发onkeyup.

请参阅我的答案如何在textArea上为代码示例强加maxlength.

  • 我在这里给-1,对不起!`onkeyup`是输入检测的可怕事件.使用`oninput`和`onpropertychange`(用于IE支持).请参阅http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript. (60认同)
  • 当发生上下文菜单剪切/粘贴时,"唯一"问题是"onchange"是******. (5认同)
  • 它对使用onkeydown和setTimeout更敏感,因此您可以获得即时更改检测,而不是等待释放密钥.如果您还需要捕获剪切和粘贴,请使用剪切和粘贴事件. (4认同)
  • 只是想强调Josh已经说过的内容,你应该使用keyup,而不是keydown:keydown似乎在更改实际发送到textarea之前被调用,所以你将使用错误的长度(并且你不要我真的知道你有多远:可以输入或删除,并且可以选择文本意味着它不仅仅是+/- 1). (3认同)

Ste*_*ger 19

  • 对于Google-Chrome,oninput就足够了(在Windows 7上测试版本为22.0.1229.94 m).
  • 对于IE 9,oninput将捕获除了通过contextmenu和backspace切割之外的所有内容.
  • 对于IE 8,除了oninput之外,还需要onpropertychange来捕获粘贴.
  • 对于IE 9 + 8,需要onkeyup来捕获退格.
  • 对于IE 9 + 8,onmousemove是我发现通过contextmenu捕获切割的唯一方法

没有在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>
Run Code Online (Sandbox Code Playgroud)

  • 很棒的函数名称:) (2认同)

use*_*743 9

我知道这不是你的问题,但我认为这可能有用.对于某些应用程序,每次按下一个键时都不会触发更改功能.这可以通过以下方式实现:

var text = document.createElement('textarea');
text.rows = 10;
text.cols = 40;
document.body.appendChild(text);

text.onkeyup = function(){
var callcount = 0;
    var action = function(){
        alert('changed');
    }
    var delayAction = function(action, time){
        var expectcallcount = callcount;
        var delay = function(){
            if(callcount == expectcallcount){
                action();
            }
        }
        setTimeout(delay, time);
    }
    return function(eventtrigger){
        ++callcount;
        delayAction(action, 1200);
    }
}();
Run Code Online (Sandbox Code Playgroud)

这可以通过测试最近的事件是否在某个延迟期内被触发来进行.祝好运!


Tim*_*lee 7

我知道这个问题是针对JavaScript的,但是,当所有当前浏览器中的textarea发生变化时,总是没有好的,干净的方法来检测.我知道jquery已经为我们照顾了它.它甚至可以处理文本区域的上下文菜单更改.无论输入类型如何,都使用相同的语法.

    $('div.lawyerList').on('change','textarea',function(){
      // Change occurred so count chars...
    });
Run Code Online (Sandbox Code Playgroud)

要么

    $('textarea').on('change',function(){
      // Change occurred so count chars...
    });
Run Code Online (Sandbox Code Playgroud)

  • 我发现更改事件与jQuery不一致,而不是普通的JS.我使用jQuery的`bind("输入剪切粘贴"......)它就像一个魅力 - 使用键盘或上下文菜单打字,剪切和粘贴;甚至拖放文本. (4认同)
  • 不幸的是,FF不会为`textarea`触发`change`事件. (2认同)

小智 5

您可以收听有关 textarea 更改的事件并根据需要进行更改。这是一个例子。

const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
    var textLn =  textArea.value.length;
    if(textLn >= 100) {
        textArea.style.fontSize = '10pt';
    }
})
Run Code Online (Sandbox Code Playgroud)
<html>
    <textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
    </textarea>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 最短的最佳答案 (2认同)