单击时输入字段未聚焦

时间:2018-12-27 20:52:46

标签: javascript html css forms

我在div中有一个<input>字段,这给我带来了麻烦。

它位于位置absolute的div内。当我单击它时,它没有获得焦点,因此无法在其中键入内容。
输入字段的其他部分应按预期工作:光标移至文本符号上方时,我可以使用鼠标右键或Tab键单击鼠标右键并将其聚焦时将其聚焦我可以正常打字。

我什至在单击时将控制台日志绑定到该日志,只是为了确保单击了正确的元素。日志确实发生了,但是仍然没有将重点放在点击上。

有人知道这里可能发生什么吗?

编辑:添加了我的代码的更多部分,非常抱歉以前没有这么少的代码。
这是我的代码:

// link that makes the form appear, on another part of the UI
jQuery("#link").on("click", function() {
  jQuery(".form").show()
})

jQuery("#close-button").on("click", function() {
  jQuery(".form").hide()
})
// This was added to test if the click was happening,
// it does not work with or without this
jQuery("#input-field").on("click", function(e) {
  console.log("clicked")
  console.log(e.target) // this is returning the "input-field" element
})
.form {
  background-color: #EAE8E8;
  position: absolute;
  width: 99%;
  right: 0;
  z-index: 100;
  bottom: 0;
  display: none;
  border: 1px solid;
}

#close-button {
  float: right;
  cursor: pointer;
}


/* input-field doesn't have any CSS defined by code yet */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="link">Click to show form</button>
<div class="form">
  <!-- this has position: absolute -->
  <img src="'/close.png" id="close-button">
  <!-- Here are some other images that can be clicked... that all works fine -->
  <input id="input-field" />
  <!-- this is not getting focused when clicked -->
</div>

1 个答案:

答案 0 :(得分:0)

您可以添加.focus()来自动调整所需的输入。这是您的示例:

jQuery("#link").on("click", function() {
  jQuery(".form").show()
  // Add to auto focus your input
  jQuery("#input-field").focus();
})

jQuery("#close-button").on("click", function() {
  jQuery(".form").hide()
})
.form {
  background-color: #EAE8E8;
  position: absolute;
  width: 99%;
  right: 0;
  z-index: 100;
  bottom: 0;
  display: none;
  border: 1px solid;
}

#close-button {
  float: right;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="link">Click to show form</button>
<div class="form">
  <img src="'/close.png" id="close-button">
  <input id="input-field" />
</div>