在 JavaScript 中取消 onBlur 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4185963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:37:38  来源:igfitidea点击:

Cancel an onBlur event in JavaScript?

javascriptjqueryevents

提问by JoelFan

I want to set up an onBlurevent for an inputelement that validates the value and, if invalid, "cancels" the blur and refocusses the input. However returning false from onBlurdoes not cancel the onBlurthe way it does with onClick. Is there a solution for this (perhaps using jQuery?)

我想为验证值的输入元素设置一个onBlur事件,如果无效,“取消”模糊并重新聚焦输入。然而,从onBlur返回 false并不会像onClick那样取消onBlur。有没有解决方案(也许使用jQuery?)

回答by casablanca

I don't know of any reliable cross-browser way to do this. Usually setting a small timeout in the onblurevent and calling focus()when the timer fires works.

我不知道有什么可靠的跨浏览器方法可以做到这一点。通常在onblur事件中设置一个小的超时时间并focus()在计时器触发时调用。

For example:

例如:

document.getElementById('your_input_id').onblur = function() {
  var self = this;
  setTimeout(function() { self.focus(); }, 10);
}

回答by SLaks

You can call focus()in the handler.
This will sometimes help.

您可以调用focus()处理程序。
这有时会有所帮助。

回答by All Workers Are Essential

You can accomplish this by using jQuery's focus()function inside a zero-second timeout. Here's an example:

您可以通过focus()在零秒超时内使用 jQuery 的函数来完成此操作。下面是一个例子:

$('#my_input').bind('blur', function(event) {
   var $input = $(this);
   var is_input_valid = false;

   // Code to determine if input is valid
   // ...

   if (!is_input_valid) {
      setTimeout(function() {
        $input.focus();
      }, 0);
      return false;
   }

});