텍스트 영역 변경 감지
자바 스크립트를 사용하여 텍스트 영역에서 변경 이벤트를 어떻게 감지합니까? 
입력 할 때 남은 문자 수를 감지하려고합니다.
onchange 이벤트를 사용해 보았지만 초점이 맞지 않을 때만 시작됩니다.
당신은 사용해야합니다 onkeyup 및 onchange 이를 위해. onchange는 상황에 맞는 메뉴 붙여 넣기를 방지하고 모든 키 입력시 onkeyup이 실행됩니다.
코드 샘플 은 textArea 에 maxlength를 부과하는 방법에 대한 답변을 참조하십시오 .
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
  });
}
이 input이벤트는 IE9 +, FF, Chrome, Opera 및 Safari 를 onpropertychange처리하고 IE8을 처리합니다 (IE6 및 7에서도 작동하지만 몇 가지 버그가 있음).
사용의 장점 input과 onpropertychange그들이 (가압 때처럼 불필요하게 발생하지 않는다는 것입니다 Ctrl또는 Shift키); 따라서 텍스트 영역 내용이 변경 될 때 상대적으로 비싼 작업을 실행하려면이 방법을 사용하십시오 .
이제 IE는 항상 그렇듯이 절반을 지원하는 작업을 수행합니다. 텍스트 영역에서 문자가 삭제 될 때 IE input에서도 onpropertychange실행 되지 않습니다 . 따라서 IE에서 문자 삭제를 처리 해야하는 경우 (사용자가 키를 누르고있는 경우에도 한 번만 실행되므로 / 사용과 반대)를 사용 하십시오.keypresskeyupkeydown
출처 : http://www.alistapart.com/articles/expanding-text-areas-made-elegant/
편집 : 주석에서 올바르게 지적했듯이 위의 솔루션조차 완벽하지 않은 것 같습니다 addEventListener. 텍스트 영역에 속성 이 있다고해서 정상적인 브라우저로 작업하고 있음을 의미하지는 않습니다 . 마찬가지로 attachEvent속성 의 존재는 IE를 의미 하지 않습니다 . 코드를 완전히 기밀로 유지하려면 코드를 변경하는 것이 좋습니다. 포인터에 대해서는 Tim Down의 주석 을 참조하십시오 .
- Google-Chrome의 경우 입력이 충분합니다 (버전 22.0.1229.94 m의 Windows 7에서 테스트 됨).
- IE 9의 경우 oninput은 컨텍스트 메뉴 및 백 스페이스를 통한 잘라내기를 제외한 모든 것을 포착합니다.
- IE 8의 경우, oninput 외에도 붙여 넣기를 잡으려면 onpropertychange가 필요합니다.
- IE 9 + 8의 경우 백 스페이스를 잡으려면 키업이 필요합니다.
- IE 9 + 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>
나는 이것이 당신의 질문이 아니라는 것을 알고 있지만 이것이 유용 할 것이라고 생각했습니다. 특정 응용 프로그램의 경우 키를 누를 때마다 변경 기능이 실행되지 않는 것이 좋습니다. 이것은 다음과 같은 방법으로 달성 할 수 있습니다.
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);
    }
}();
특정 지연 시간 내에 최신 이벤트가 발생했는지 테스트하여 작동합니다. 행운을 빕니다!
이 질문은 JavaScript에만 해당된다는 것을 알고 있지만 현재 모든 브라우저에서 텍스트 영역이 변경 될 때 항상 감지 할 수있는 좋은 방법은 없습니다. jquery가 우리를 위해 그것을 돌 보았다는 것을 배웠습니다. 텍스트 영역의 상황에 맞는 메뉴 변경 사항도 처리합니다. 입력 유형에 관계없이 동일한 구문이 사용됩니다.
    $('div.lawyerList').on('change','textarea',function(){
      // Change occurred so count chars...
    });
또는
    $('textarea').on('change',function(){
      // Change occurred so count chars...
    });
텍스트 영역 변경시 이벤트를 듣고 원하는대로 변경할 수 있습니다. 한 가지 예가 있습니다.
(() => {
	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>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.
<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;
  }
});
Code I have used for IE 11 without jquery and just for a single textarea:
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:
<TEXTAREA onpropertychange='limit_char(5)' ...
Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.
<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;
}
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.
self.setInterval('checkTextAreaValue()', 50);
참고URL : https://stackoverflow.com/questions/2823733/textarea-onchange-detection
'Programming' 카테고리의 다른 글
| 도커 컨테이너에 여러 볼륨을 마운트 하시겠습니까? (0) | 2020.07.03 | 
|---|---|
| IsNothing 대 Is Nothing (0) | 2020.07.03 | 
| 단위 테스트를 작성하는 방법? (0) | 2020.07.03 | 
| Xcode 4-성능 저하 (0) | 2020.07.03 | 
| "목록 유형의 표현식에 확인되지 않은 변환이 필요합니다 ..."는 어떻게 수정합니까? (0) | 2020.07.03 |