css问题:safari 下 input 无法自动聚焦解决

shit

背景

最近在开发一个移动端的页面,要求是,页面加载后,自动聚焦到输入框。

正常做法

正常的做法是,获取 input 元素,然后执行 focus() 方法

1
2
// 因为用的是 vue, 直接通过refs获取即可
$refs.input.$el.focus()

这个方法在 chrome 下是可以生效的

问题

但是,在 safari 下有兼容性问题,始终无法聚焦,这里记录一下解决方案:

相关问题:https://stackoverflow.com/questions/54424729/ios-show-keyboard-on-input-focus

思路是:创建一个额外的 input,再切换到目标 input(需要再研究一下为什么)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const autoFocus = (target) => {
// 创建 input 元素并 focus
var fakeEl = document.createElement('input')
fakeEl.style.height = 0
fakeEl.style.opacity = 0
fakeEl.style.position = 'absolute'
fakeEl.style.top = 0
document.body.appendChild(fakeEl)
fakeEl.focus()
// 切换至目标元素
setTimeout((_) => {
target.click()
target.focus()
document.body.removeChild(fakeEl)
}, 100)
}

以上。