大概在网上建立一个网站一年要花多少钱呀搜索引擎优化工作
在日常开发中有时可能会遇到input 或 textarea 不能满足的开发场景,比如多行输入的情况下,textarea 的右下角icon 无法去除, 所以此时可以使用div 设置可编辑状态,完成功能开发,在开发的过程中仍会遇到一下问题。
1,如何设置div使其变成可编辑状态
通过给div 添加 :contenteditable="true" 可以开启编辑状态,
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,粘贴事件
@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,输入处理,获取输入的文本内容
通过 @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,中文输入法处理
通过 @compositionstart="messageInputStart",及@compositiοnend="messageInputEnd" 对中文输入法状态进行处理
/*** @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);};