Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

input 搜索如何防抖,如何处理中文输入 #34

Open
hanyueqiang opened this issue Dec 21, 2020 · 0 comments
Open

input 搜索如何防抖,如何处理中文输入 #34

hanyueqiang opened this issue Dec 21, 2020 · 0 comments

Comments

@hanyueqiang
Copy link
Owner

防抖处理

const inputEle = document.querySelector('#input')
let dbFun = debounce(500)
inputElet.addEventListener('keyup', function (e) {
  dbFun(e.target.value);
})

function debounce(timeout) {
  let timer;
  return function (value) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      console.log(value)
    }, timeout);
  }
}

处理中文输入

function onCompositionStart(e) {
    console.log('onCompositionStart', e)
    e.target.composing = true;
  }
function onCompositionEnd(e) {
  console.log('onCompositionEnd', e)
  e.target.composing = false;
}
// 第一次输入中文触发
inputEle.addEventListener('compositionstart', onCompositionStart);
// 输入中文确定后触发
inputEle.addEventListener('compositionend', onCompositionEnd);

3个原生方法

  • compositionstart
    切换中文输入法时在打拼音时(此时input内还没有填入真正的内容),会首先触发compositionstart
  • compositionupdate
    每打一个拼音字母,触发compositionupdate,
  • compositionend
    最后将输入好的中文填入input中时触发compositionend。触发compositionstart时,文本框会填入 “虚拟文本”(待确认文本),同时触发input事件;在触发compositionend时,就是填入实际内容后(已确认文本),所以这里如果不想触发input事件的话就得设置一个bool变量来控制。

问题描述:
文本框输入表单验证,在输入中文的时候input对待确认字符进行验证,不希望对该字符进行验证,而是在输入中文确定后进行验证
解决方法:
参照vue源码 v-model实现思路:

if (needCompositionGuard) {
    code = `if($event.target.composing)return;${code}`
 }
function onCompositionStart(e) {
    e.target.composing = true;
  }
function onCompositionEnd(e) {
   e.target.composing = false;
   trgger(e.target, 'input')
}
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant