如何确定焦点何时离开HTML表单(即窗体的子窗体不再有焦点)



例如,我有一个HTML表单元素,它有一个文本区,两个按钮作为子元素。当焦点从这三个元素中的一个转移到这三个元素之外的另一个元素时,我该如何检测?换句话说,我如何检测焦点何时离开表单,以便自动取消它?

我想我可以使用表单上的focusout事件来弄清楚焦点何时不再属于它的一个子元素,但是获得焦点的对象似乎不能从focusout事件访问,所以我没有办法检查焦点是否只是从文本区到一个按钮,例如。

relatedObjectfromElementtoElement属性均未定义

虽然我担心这种方法可能有微妙的错误,但这是我所知道的最好的方法:

  • 在表单的focusout事件上注册(不是blur,因为后者不冒泡)
  • 通过setTimeout注册一个0延迟函数,因此焦点转移被处理
  • 中的timeoutout函数,检查document.activeElement是否是窗体的后代。如果没有,则开火。

下面是一个示例实现:

$('#yourform').on('focusout', function(evt) {
  var self = $(this);
  setTimeout(function() {
    if (self.has($(document.activeElement)).length == 0) {
      alert('leave');
    }
  }, 0);
});
form {
  border: 1px solid red;
  margin: 1em;
  padding: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='yourform'>
  <input type='text'>
  <input type='text'>
</form>
<input type='text'>

const form = document.querySelector(".myform");
document.onclick = () => {
  // query selecting the form element and checking for the
  // css :focus pseudo class inside the form element
  if (!form.querySelector(":focus")) {
  
    // this console log would run when any placeholder in the form is not focused 
    console.log("form dismissed.")
  }
}
.myform {
  padding: 10px;
  background: blueviolet;
  color: #fff;
}
.myform * {
  display: block;
  margin: 5px 0;
}
<form class="myform">
  when not selecting the placeholders this will log a msg to the console
  <input value="select here" type="text"/>
  <input value="select here" type="text"/>
  <textarea>Select here</textarea>
  <button>Submit</button>
</form>

正如您在上面的代码片段中注意到的,您可以使用element.querySelector(":focus")来检查表单的内容是否有焦点。这个方法完全可以工作。

(如果你觉得这个答案对你有用,请投票)

正确的名字是"blur"

function setBlur()
{
   var elements = document.getElementByTagName('input');
   for(var i = 0; i < elements.length; i++)
      elements[i].setAttribute('onfocus', 'callme(this)');
}
function callme(el)
{
   var _id = el.getAttribute('id');
   if(_id != "textarea_id' && _id != "button_1_id" && _id != "button_2_id")
        callYourMethodToHandleFocusOutsideYourForm();
}
body.onload = function() { setBlur(); }

这将做的伎俩

你也可以为textarea这样做只要应用document.getElementByTagname('textarea')并循环数组

最新更新