当我打电话input.focus()
时从触摸事件监听器中,它将输入聚焦几毫秒,但焦点会立即返回到触摸的元素。我也在我的手机(真正的触摸设备)上进行了测试,行为是相同的。我尝试用谷歌搜索一些相关文档,但没有找到任何有用的东西。
我当前使用的唯一解决方法是 setTimeout(() => input.focus(), 500)
,这是一种非常草率的方法。有什么想法吗?
https://codepen.io/xpuu/pen/BXpBZY
document.addEventListener("DOMContentLoaded", function() {
let input = document.getElementById("test");
let events = {
click(e) {
console.log("click");
input.focus();
},
touchstart(e) {
console.log("touchstart");
input.focus();
},
touchend(e) {
console.log("touchend");
input.focus();
},
touchprevent(e) {
console.log("touchprevent");
e.preventDefault();
input.focus();
},
touchtimeout(e) {
console.log("touchtimeout");
setTimeout(() => input.focus(), 500);
}
};
let buttons = document.getElementById("buttons");
let validEvents = ["click", "touchstart", "touchend"];
Object.keys(events).forEach(key => {
let handler = key;
let btn = document.createElement("button");
btn.innerText = key;
if (!validEvents.includes(handler)) {
handler = "touchstart";
}
//console.log(handler, key);
btn.addEventListener(handler, events[key]);
buttons.appendChild(btn);
});
});
input {
padding: 3px;
}
<p>Enable devtools / responsive mode and touch emulation for this to work</p>
<input id="test" value="focus me please">
<p id="buttons"></p>
最佳答案
正如 Chris 提到的,您必须在聚焦输入之前运行 e.preventDefault()
。此外,在 addEventListener
选项中禁用 passive
处理程序也很重要。
let touchprevent = e => {
console.log("touchprevent");
e.preventDefault();
input.focus();
}
input.addEventListener('touchstart', touchprevent, { passive: false });
关于javascript - 无法在触摸事件中聚焦 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57310622/