Javascript 文本区域变化检测

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2823733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:04:10  来源:igfitidea点击:

Textarea onchange detection

javascript

提问by teepusink

How do I detect change event on textarea using javascript?
I'm trying to detect how many characters left is available as you type.

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

I tried using the onchange event, but that seems to only kick in when focus is out.

我尝试使用 onchange 事件,但这似乎只在焦点消失时才开始。

采纳答案by Josh Stodola

You will need to use onkeyupandonchangefor this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.

为此,您将需要使用onkeyuponchange。onchange 将阻止上下文菜单粘贴,并且 onkeyup 将在每次击键时触发。

See my answer on How to impose maxlength on textAreafor a code sample.

有关代码示例,请参阅我关于如何在 textArea施加 maxlength 的答案。

回答by Vicky Chijwani

It's 2012, the post-PC era is here, and we still have to struggle with something as basic as this. This ought to be very simple.

现在是 2012 年,后 PC 时代已经到来,我们仍然要为这样基本的东西苦苦挣扎。这应该很简单

Until such time as that dream is fulfilled, here's the best way to do this, cross-browser: use a combination of the inputand onpropertychangeevents, like so:

在梦想实现之前,这是跨浏览器执行此操作的最佳方法:使用inputonpropertychangeevents的组合,如下所示:

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
  });
}

The inputevent takes care of IE9+, FF, Chrome, Opera and Safari, and onpropertychangetakes care of IE8(it also works with IE6 and 7, but there are some bugs).

input事件处理IE9+、FF、Chrome、Opera 和 Safari,并onpropertychange处理IE8(它也适用于 IE6 和 7,但存在一些错误)。

The advantage of using inputand onpropertychangeis that they don't fire unnecessarily (like when pressing the Ctrlor Shiftkeys); so if you wish to run a relatively expensive operation when the textarea contents change, this is the way to go.

使用inputand的好处onpropertychange是它们不会不必要地触发(比如按下CtrlShift键时);所以如果你想在 textarea 内容改变时运行一个相对昂贵的操作,这是要走的路

Now IE, as always, does a half-assed job of supporting this: neither inputnor onpropertychangefires in IE when characters are deletedfrom the textarea. So if you need to handle deletion of characters in IE, use keypress(as opposed to using keyup/ keydown, because they fire only once even if the user presses and holds a key down).

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

Source: http://www.alistapart.com/articles/expanding-text-areas-made-elegant/

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

EDIT:It seems even the above solution is not perfect, as rightly pointed out in the comments: the presence of the addEventListenerproperty on the textarea does notimply you're working with a sane browser; similarly the presence of the attachEventproperty does notimply IE. If you want your code to be really air-tight, you should consider changing that. See Tim Down's commentfor pointers.

编辑:似乎即使上述解决方案也不完美,正如评论中正确指出的那样:addEventListenertextarea 上属性的存在并不意味着您正在使用正常的浏览器;同样,该attachEvent属性的存在并不意味着 IE。如果您希望您的代码真正密封,您应该考虑更改它。请参阅Tim Down 的评论以获取指示。

回答by Stefan Steiger

  • For Google-Chrome, oninput will be sufficient (Tested on Windows 7 with Version 22.0.1229.94 m).
  • For IE 9, oninput will catch everything except cut via contextmenu and backspace.
  • For IE 8, onpropertychange is required to catch pasting in addition to oninput.
  • For IE 9 + 8, onkeyup is required to catch backspace.
  • For IE 9 + 8, onmousemove is the only way I found to catch cutting via contextmenu
  • 对于 Google-Chrome,oninput 就足够了(在版本 22.0.1229.94 m 的 Windows 7 上测试)。
  • 对于 IE 9,oninput 将通过上下文菜单和退格键捕获除剪切之外的所有内容。
  • 对于 IE 8,除了 oninput 之外,还需要 onpropertychange 来捕获粘贴。
  • 对于 IE 9 + 8,需要 onkeyup 来捕捉退格。
  • 对于 IE 9 + 8,onmousemove 是我发现通过上下文菜单捕捉剪切的唯一方法

Not tested on Firefox.

未在 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>

回答by user45743

I know this isn't exactly your question but I thought this might be useful. For certain applications it is nice to have the change function fire not every single time a key is pressed. This can be achieved with something like this:

我知道这不完全是您的问题,但我认为这可能有用。对于某些应用程序,不是每次按下键时都触发更改功能是很好的。这可以通过这样的事情来实现:

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);
    }
}();

This works by testing if a more recent event has fired within a certain delay period. Good luck!

这通过测试是否在某个延迟时间内触发了较新的事件来起作用。祝你好运!

回答by Tim Duncklee

I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.

我知道这个问题是特定于 JavaScript 的,但是,似乎没有好的、干净的方法来始终检测当前所有浏览器中的 textarea 何时更改。我了解到 jquery 已经为我们处理好了。它甚至可以处理对文本区域的上下文菜单更改。无论输入类型如何,都使用相同的语法。

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

or

或者

    $('textarea').on('change',function(){
      // Change occurred so count chars...
    });

回答by Pankaj Manali

You can listen to event on change of textarea and do the changes as per you want. Here is one example.

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

(() => {
 const textArea = document.getElementById('my_text_area');
  textArea.addEventListener('input', () => {
    let textLn =  textArea.value.length;
    if(textLn >= 100) {
      textArea.style.fontSize = '10pt';
    }

  })
})()
<html>
<textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
</textarea>
</html>

回答by Ronnie Royston

Keyup should suffice if paired with HTML5 input validation/pattern attribute. So, create a pattern (regex) to validate the input and act upon the .checkValidity() status. Something like below could work. In your case you would want a regex to match length. My solution is in use / demo-able online here.

如果与 HTML5 输入验证/模式属性配对,Keyup 就足够了。因此,创建一个模式(正则表达式)来验证输入并根据 .checkValidity() 状态采取行动。像下面这样的东西可以工作。在您的情况下,您需要一个正则表达式来匹配长度。我的解决办法是使用/演示能够在线在这里

<input type="text" pattern="[a-zA-Z]+" id="my-input">

var myInput = document.getElementById = "my-input";

myInput.addEventListener("keyup", function(){
  if(!this.checkValidity() || !this.value){
    submitButton.disabled = true;
  } else {
    submitButton.disabled = false;
  }
});

回答by Rogério Silva

Code I have used for IE 11 without jquery and just for a single textarea:

我在没有 jquery 的情况下用于 IE 11 并且仅用于单个 textarea 的代码:

Javascript:

Javascript:

// 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);
}

and html:

和 html:

<TEXTAREA onpropertychange='limit_char(5)' ...

回答by default

Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.

试试这个。这很简单,因为它是 2016 年,我相信它可以在大多数浏览器上运行。

<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea> 
<div><span id="spn"></span> characters left</div>

function check(){
    var string = document.getElementById("url").value
    var left = 15 - string.length;
    document.getElementById("spn").innerHTML = left;
}

回答by Ico

The best thing that you can do is to set a function to be called on a given amount of time and this function to check the contents of your textarea.

你能做的最好的事情是设置一个函数在给定的时间内被调用,这个函数来检查你的 textarea 的内容。

self.setInterval('checkTextAreaValue()', 50);