如何检查焦点是否离开了一组元素

How to check if the focus left a group of elements

本文关键字:一组 元素 离开 焦点 何检查 检查 是否      更新时间:2023-09-26

我想要一个有4个输入的表单,通常只显示第一个。当它获得焦点时,其他3个输入变为可见。

如果焦点离开表单(用户在任何输入之外单击/点击/选项卡),则输入应隐藏。

我曾想过在表单的blur事件或输入字段中使用document.activeElement来检查输入丢失后焦点的位置。然而,blur事件中的document.activeElement似乎总是返回body,而不是实际要接收它的元素。

这就是我得到的:

// whenever an input loses focus:
//   if the focus is still inside the form,
//      keep the inputs visible
//   if focus left the form
//      hide the inputs, leaving only the first visible
$('#new-journal input').blur(function (e) {
    var $active = $(document.activeElement);
    if ($active.closest('#new-journal').length === 0) {
        $('#new-journal input:gt(0)').addClass('hide');
    }
});

考虑到#new journal是表单元素的ID。

// whenever the user clicks/focuses the "Add a journal" input, 
// the other inputs inside the form appear
$('#name').focus(function(e) {
  $('#new-journal input:gt(0)').removeClass('hide');
});
// whenever an input loses focus:
//   if the focus is still inside the form,
//      keep the inputs visible
//   if focus left the form
//      hide the inputs, leaving only the first visible
$('#new-journal input').blur(function(e) {
  var $active = $(document.activeElement);
  if ($active.closest('#new-journal').length === 0) {
    $('#new-journal input:gt(0)').addClass('hide');
  }
});
// just logs who is the element with focus (document.activeElement)
$('*').on('focus blur', function(e) {
  var $history = $('#history'),
    current = document.activeElement,
    label = current.tagName + ' ' + current.id;
  $history.html($history.html() + label + ''n');
});
input[type=text] {
  padding: 4px 6px;
  display: block;
  margin: 0 0 5px;
  box-sizing: border-box;
}
.hide {
  display: none !important;
  height: 0;
  margin: 0;
  padding: 0;
}
pre:not(:empty) {
  border-radius: 2px;
  background-color: #eee;
  padding: 5px;
}
.col {
  float: left;
  width: 45%;
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col">
  <form id="new-journal">
    <input type="text" id="name" placeholder="Add a journal" />
    <input type="text" id="field1" placeholder="Sub title" class="hide" />
    <input type="text" id="field2" placeholder="Owner" class="hide" />
    <input type="text" id="field3" placeholder="Price" class="hide" />
  </form>
</div>
<div class="col">
  <p>document.activeElement:</p>
  <pre id="history"></pre>
</div>

除了使用document.activeElement之外,如何检测焦点是否仍在窗体(任何可聚焦的容器元素)内有什么想法吗?


更新:我还试着只使用CSS,并遵循以下规则:

#new-journal input:not(#name) {
    display: none;
}
#new-journal input:focus ~ input {
    display: block !important;
}

但我得到了完全相同的结果。

您可以通过将focus函数应用于所有输入而不仅仅是第一个输入(#name)来解决问题。

$('#new-journal input').focus(function (e) {
    $('#new-journal input:gt(0)').removeClass('hide');
});

这解决了问题,并且不会影响初始布局。你可以在这里看到它的工作原理:http://jsfiddle.net/vyd5dje6/.