免插件WordPress對接公眾號贛州seo外包
? ? ? ? 在日常開發(fā)中有時可能會遇到input 或 textarea 不能滿足的開發(fā)場景,比如多行輸入的情況下,textarea 的右下角icon 無法去除, 所以此時可以使用div 設(shè)置可編輯狀態(tài),完成功能開發(fā),在開發(fā)的過程中仍會遇到一下問題。
1,如何設(shè)置div使其變成可編輯狀態(tài)
?通過給div 添加 :contenteditable="true" 可以開啟編輯狀態(tài),
?2,設(shè)置placeholder
&__text{&:empty::before{display: inline-block;width:100%;content: attr(placeholder-pc);color: var(--t-font-color-gy3);cursor: text;}&:not(:empty)::before{content:none;}}
?3,粘貼事件
@paste="handlePaste"/*** 處理粘貼事件* @param event 剪貼板事件*/function handlePaste(event: ClipboardEvent) {event.preventDefault();const clp = event.clipboardData;const text = clp?.getData('text/plain') || '';if (text !== '') {document.execCommand('insertText', false, text);}}
?4,獲取輸入文本長度px
/*** @description: 計算輸入文本所占的px長度* @param {*} text 輸入的文本* @return {*}*/
export function calculateInputLength(text:string) {const dom = document.createElement('div');dom.style.position = 'absolute';dom.style.visibility = 'hidden';dom.style.display = 'inline-block';dom.style.width = 'auto';dom.style.height = '0px';dom.style.fontSize = '14px';dom.style.whiteSpace = 'nowrap';dom.innerHTML = text;document.body.appendChild(dom);const testWidth = dom.offsetWidth;document.body.removeChild(dom);return testWidth;
}
?5,輸入處理,獲取輸入的文本內(nèi)容
?通過 @input 事件綁定輸入處理方法
?const handleInput = async (event: InputEvent) => {
? ? ? // state.isComposing 用來判斷當前是否是中文輸入法輸入 第7步介紹
? ? ? if (state.isComposing || event.data === '') {
? ? ? // 如果進行的是中文輸入法輸入,或者輸入的是空格,則不保存輸入文本
? ? ? ? return;
? ? ? }
? ? ? // 添加輸入文本長度檢測
? ? ? // 否則的話可以根據(jù)event.target.innerText.trim() 獲取輸入的文本
? ? ? state.messageInfo = ?cloneDeep((event?.target as HTMLElement)?.innerText?.trim());
? ? ? // 第6部將光標設(shè)置到文本末尾
? ? ? next(()=>{
? ? ? ? ? ?// 將光標設(shè)置到文本末尾
? ? ? })
}
?6,設(shè)置光標位置于內(nèi)容文本末尾
/*** @description: 可編輯多行文本,設(shè)置光標聚焦文本末尾* @param {HTMLElement} dom 要編輯的dom元素* @return {*}*/
export const setCursorTAtTextEnd = (dom:HTMLElement) => {dom?.focus();const range = document.createRange();const selection = window.getSelection() as any;range.selectNodeContents(dom);range.collapse(false);selection.removeAllRanges();selection.addRange(range);
};
?7,中文輸入法處理
????????通過 @compositionstart="messageInputStart",及@compositiοnend="messageInputEnd" 對中文輸入法狀態(tài)進行處理
/*** @description: 鍵盤中文輸入法開始* @param {*} event* @return {*}*/const messageInputStart = (event:Event) => {// 只有中文輸入法才會觸發(fā)state.isComposing = true;};/*** @description: 鍵盤輸入結(jié)束* @param {*} event* @return {*}*/const messageInputEnd = (event: CompositionEvent) => {// 中文輸入法結(jié)束state.isComposing = false;handleInput(event as any);};