需添加 contenteditable="true"
<div id="add-content" contenteditable="true" style="border: 1px solid gray;" >
監聽事件keydown 、textInput 、input:
<script> var content = document.getElementById('add-content') //注冊中文的輸入事件, var isCN = false; content.addEventListener('compositionstart',function(){ isCN = true; }); content.addEventListener('compositionend',function(){ isCN = false; }) //注冊文本輸入事件,獲取光標的起止偏移數據,如果是非中文以及超出長度的輸入,則撤銷本次操作 var txtAnchorOffset, txtFocusOffset; content.addEventListener("textInput",function(event){ var _sel = document.getSelection(); txtAnchorOffset = _sel.anchorOffset; txtFocusOffset = _sel.focusOffset; //必須加上isCN的判斷,否則獲取不到正確的光標數據 if(!isCN && this.textContent.length >= noteMax){ event.preventDefault(); } }); //注冊粘貼事件,獲取粘貼數據的長度 var pastedLength; content.addEventListener("paste",function(event){ if(!event.clipboardData) return; pastedLength = event.clipboardData.getData('Text').length; }); //注冊輸入事件,對輸入的數據進行 content.addEventListener("input",function(event){ setTimeout(function(){ if(!isCN){ var _this = content; if(_this.textContent.length > noteMax){ var data = _this.textContent; if(pastedLength > 1){ oldDate = data.slice(0, txtAnchorOffset) + data.slice(txtFocusOffset+pastedLength, data.length); //粘貼字符串長度置為0,以免影響到下一次判斷。 pastedLength = 0; } else { oldDate = data.slice(0, txtAnchorOffset) + data.slice(txtFocusOffset, data.length); } //再次截取最大長度字符串,防止溢出 _this.textContent = oldDate.slice(0, noteMax); //光標移動到起始偏移位置 document.getSelection().collapse(_this.firstChild, txtAnchorOffset);47 } } }, 0); //content.focus(); }); </script>