优秀的网站设计,电子商务管理系统,网站开发需要的技能,seo关键词快速排名前三位在日常开发中有时可能会遇到input 或 textarea 不能满足的开发场景#xff0c;比如多行输入的情况下#xff0c;textarea 的右下角icon 无法去除, 所以此时可以使用div 设置可编辑状态#xff0c;完成功能开发#xff0c;在开发的过程中仍会遇到一下问题。
1#xff0c;如… 在日常开发中有时可能会遇到input 或 textarea 不能满足的开发场景比如多行输入的情况下textarea 的右下角icon 无法去除, 所以此时可以使用div 设置可编辑状态完成功能开发在开发的过程中仍会遇到一下问题。
1如何设置div使其变成可编辑状态 通过给div 添加 :contenteditabletrue 可以开启编辑状态, 2设置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粘贴事件
pastehandlePaste/*** 处理粘贴事件* 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输入处理获取输入的文本内容 通过 input 事件绑定输入处理方法 const handleInput async (event: InputEvent) { // state.isComposing 用来判断当前是否是中文输入法输入 第7步介绍 if (state.isComposing || event.data ) { // 如果进行的是中文输入法输入或者输入的是空格则不保存输入文本 return; } // 添加输入文本长度检测 // 否则的话可以根据event.target.innerText.trim() 获取输入的文本 state.messageInfo cloneDeep((event?.target as HTMLElement)?.innerText?.trim()); // 第6部将光标设置到文本末尾 next((){ // 将光标设置到文本末尾 }) } 6设置光标位置于内容文本末尾
/*** description: 可编辑多行文本设置光标聚焦文本末尾* 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中文输入法处理 通过 compositionstartmessageInputStart及compositiοnendmessageInputEnd 对中文输入法状态进行处理
/*** description: 键盘中文输入法开始* param {*} event* return {*}*/const messageInputStart (event:Event) {// 只有中文输入法才会触发state.isComposing true;};/*** description: 键盘输入结束* param {*} event* return {*}*/const messageInputEnd (event: CompositionEvent) {// 中文输入法结束state.isComposing false;handleInput(event as any);};