preflower / blog

preflower's blog
0 stars 0 forks source link

关于 input.focus 在iOS下无法唤起 keyboard 问题的探索 #26

Open preflower opened 2 years ago

preflower commented 2 years ago

iOS 唤起 keyboard 方法

  1. 用户点击操作
  2. input在创建时立刻触发focus(即要求函数执行时处于同一线程内)

解决办法

根据方法2我们可以先创建一个临时隐藏的input,并且在创建时立刻触发focus方法,在需要的时候(例如实际input已渲染完毕)转移 Keyboard 的控制权,来达到input focus唤起 Keyboard 的效果

function focusAndOpenKeyboard (el: HTMLInputElement, timeout: number): void {
  if (!timeout) {
    timeout = 100
  }
  if (el) {
    // Align temp input element approximately where the input element is
    // so the cursor doesn't jump around
    const temp = document.createElement('input')
    temp.style.position = 'absolute'
    temp.style.top = `${el.offsetTop + 7}px`
    temp.style.left = `${el.offsetLeft}px`
    temp.style.height = '0'
    temp.style.opacity = '0'
    // Put this temp element as a child of the page <body> and focus on it
    document.body.appendChild(temp)
    temp.focus()

    // The keyboard is open. Now do a delayed focus on the target element
    setTimeout(function () {
      el.focus()
      el.click()
      // Remove the temp element
      document.body.removeChild(temp)
    }, timeout)
  }
}
preflower commented 2 years ago

归纳 #3