如何設(shè)置DIV可編輯

方案一:contenteditable屬性
<div id="add-content" contenteditable="true">這里可以編輯</div>
contenteditable 屬性是 html5 中的新屬性,contenteditable 屬性規(guī)定元素內(nèi)容是否可編輯。
注釋:如果元素未設(shè)置 contenteditable 屬性,那么元素會從其父元素繼承該屬性。
js操作:
監(jiān)聽事件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;})//注冊文本輸入事件,獲取光標的起止偏移數(shù)據(jù),如果是非中文以及超出長度的輸入,則撤銷本次操作var txtAnchorOffset, txtFocusOffset;content.addEventListener("textInput",function(event){var _sel = document.getSelection();txtAnchorOffset = _sel.anchorOffset;txtFocusOffset = _sel.focusOffset;//必須加上isCN的判斷,否則獲取不到正確的光標數(shù)據(jù)if(!isCN && this.textContent.length >= noteMax){event.preventDefault();}});//注冊粘貼事件,獲取粘貼數(shù)據(jù)的長度var pastedLength;content.addEventListener("paste",function(event){if(!event.clipboardData) return;pastedLength = event.clipboardData.getData('Text').length;});//注冊輸入事件,對輸入的數(shù)據(jù)進行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>
方案二:css中user-modify屬性
<div id="add-content" >這里可以編輯</div><style>#add-content{user-modify: read-write;-webkit-user-modify: read-write;}</style>
user-modify: read-only | read-write | read-write-plaintext-only
參數(shù)說明:
| read-only | 內(nèi)容只讀。 |
|---|---|
| read-write | 內(nèi)容可讀寫。(支持富文本) |
| read-write-plaintext-only | 內(nèi)容可讀寫,但粘貼內(nèi)容中的富文本格式(如文本的顏色、大小,圖片等)會丟失。內(nèi)容類似于以純文本顯示。 |
學習更多技能
請點擊下方公眾號
![]()

評論
圖片
表情
