Instance code for real-time monitoring text box input words, text box instance
Requirement: monitors and limits the number of words in the text input box in real time.
1. Monitor the number of words currently entered in real time. Use the onkeyup event method directly and add the maxlength attribute to the input box to limit the length. For example:
<div> <textarea id="txt" maxlength="10"></textarea> <p><span id="txtNum">0</span>/10</p> </div>
var txt = document.getElementById("txt"); var txtNum = document.getElementById("txtNum"); txt.addEventListener("keyup", function(){ txtNum.textContent = txt.value.length; })
Now you can complete the basic monitoring function. The problem is that when you enter English, the number of monitored data changes with the length of pinyin.
2. solution:
The compositionstart event is triggered before a text input (similar to a keydown event, but only before the input of several visible characters, the input of these visible characters may require a series of keyboard operations, speech recognition, or alternative words for clicking the input method ).
Compositionend is a text input event.
These two attributes are a bit similar to the "Switch". For example, if the switch is enabled when the Chinese input is started, the length value obtained by the monitoring is not changed. After one or a string of text is entered completely, switch off to obtain the length of the monitored value.
Var txt = document. getElementById ("txt"); var txtNum = document. getElementById ("txtNum"); var sw = false; // define the closed txt switch. addEventListener ("keyup", function () {if (sw = false) {countTxt () ;}}); txt. addEventListener ("compositionstart", function () {sw = true ;}); txt. addEventListener ("compositionend", function () {sw = false; countTxt () ;}); function countTxt () {// count function if (sw = false) {// txtNum is assigned only when the switch is off. textContent = txt. value. length ;}}
In vue:
Template:
<textarea name="suggestions-text" id="textarea" cols="30" rows="10" maxlength="300" v-on:keyup="write()" v-on:compositionstart="importStart()" v-on:compositionend="importEnd()" v-model="textContent"></textarea><p class="counterNum">{{conterNum}}/300</p>
Data:
textContent: '',conterNum: 0,chnIpt: false,
Methods:
write() { let self = this; if (self.chnIpt == false) { self.conterNum = self.textContent.length; }},importStart() { this.chnIpt = true;},importEnd() { this.chnIpt = false; this.write();}
The example code for Inputting Words in the real-time monitoring text box above is all the content shared by the editor. I hope you can give us a reference and support for the help house.