我有一个问题,我无法解决。
键盘不显示在IOS上的input.focus()上
searchMobileToggle.addEventListener('click', function() {
setTimeout(function(){
searchField.focus();
}, 300);
});
我一直在寻找一个没有结果的解决方案,我知道这是一个经常未解决的问题,但我看到NIKE(https://m.nike.com/fr/fr_fr/)和FOODSPRING(https://www.foodspring.fr/)在移动设备上做这件事。
所以我想知道他们是怎么做的?
我找到了一个解决方案,click()
不起作用,但我想通了。
searchMobileToggle.addEventListener('click', function() {
if(mobileSearchblock.classList.contains('active')) {
searchField.setAttribute('autofocus', 'autofocus');
searchField.focus();
}
else {
searchField.removeAttribute('autofocus');
}
});
当加载组件时,我正在使用vue.js删除输入autofocus
属性。所以我点击它,但有另一个问题,自动对焦只工作一次,但结合focus(),它现在一直工作:)
谢谢你的帮助 !
没有其他答案对我有用。我最后查看了Nike javascript代码,这是我提出的可重用函数:
function focusAndOpenKeyboard(el, timeout) {
if(!timeout) {
timeout = 100;
}
if(el) {
// Align temp input element approximately where the input element is
// so the cursor doesn't jump around
var __tempEl__ = document.createElement('input');
__tempEl__.style.position = 'absolute';
__tempEl__.style.top = (el.offsetTop + 7) + 'px';
__tempEl__.style.left = el.offsetLeft + 'px';
__tempEl__.style.height = 0;
__tempEl__.style.opacity = 0;
// Put this temp element as a child of the page <body> and focus on it
document.body.appendChild(__tempEl__);
__tempEl__.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(__tempEl__);
}, timeout);
}
}
// Usage example
var myElement = document.getElementById('my-element');
var modalFadeInDuration = 300;
focusAndOpenKeyboard(myElement, modalFadeInDuration); // or without the second argument
请注意,这绝对是一个hacky解决方案,但事实上,苹果公司并没有这么长时间地解决这个问题。
没有合法的方法可以做到这一点,因为iOS只想在用户交互中打开键盘,但是你仍然可以通过使用prompt()
或在focus()
事件中使用click()
来实现这一点,并且会显示出来。