当在mousedown事件中将输入字段添加到文档中并定位在被单击元素的顶部时,有时它会被聚焦。
var container = document.querySelector(".container");
var targ = document.querySelector("#target");
targ.addEventListener("mousedown", (e) => {
var input = document.createElement("input");
container.appendChild(input, targ);
});
.container {
position: relative;
}
.container>* {
position: absolute;
}
#target {
margin: 10px;
}
.container>input {
height: 50px;
}
<div class="container">
<div id="target">Click here!</div>
</div>
这是一支钢笔:https://codepen.io/motz-art/pen/jgyYoY
为什么会发生这种情况?为什么它并不总是发生呢?
Chrome版本75.0.3770.142 (官方版本)(32位)
发布于 2019-07-29 18:14:33
这是因为当鼠标指针位于新添加的输入字段上时,mousemove
事件会将其聚焦。请注意,当您按住鼠标按钮但没有移动鼠标和释放鼠标按钮而没有任何移动时,输入不会被聚焦。如果你没有这样稳定的手,试着在笔记本电脑上用触摸板点击;)
一种解决方案是捕获click
或mouseup
事件,而不是mousedown
。
https://stackoverflow.com/questions/57251596
复制相似问题