Javascript 如何捕捉瞬间输入框失去焦点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13668491/
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-08-24 12:37:10  来源:igfitidea点击:

how to catch moment input box lost focus?

javascripthtml

提问by lwiii

i am using event listener structure like this to do some stuff when input box loses focus. but it won't work. what event should i listen to to get the moment input box loses cursor inside it (user clicks outside of it)?

当输入框失去焦点时,我正在使用这样的事件侦听器结构来做一些事情。但它不会工作。我应该听什么事件来获取输入框在其中丢失光标的那一刻(用户在它外面点击)?

document.getElementById('div inside which input is located').addEventListener( 'blur',  function(e){ if(event.target.className=='editInput'){doStuff(event.target);} } , false );

采纳答案by user4035

The correct event is onBlur. Look at this code:

正确的事件是 onBlur。看看这段代码:

<!DOCTYPE html>
<html>
  <head>
    <title>element</title>
<script type="text/javascript">
  function message() {
            var text = document.getElementById("test").value;
            alert(text);
    }
</script>
  </head>
  <body>
      <input type="text" name="test" id="test">
<script type="text/javascript">
document.getElementById("test").onblur=message;
</script>
  </body>
</html>

It works and prints the content of the input when it loses focus. Maybe your error is that you attached the event to the div and not to the input?

它在失去焦点时工作并打印输入的内容。也许您的错误是您将事件附加到 div 而不是输入?

回答by Meliborn

var input = document.getElementsByTagName('input')[0];

input.onfocus = function() {
  this.className = 'highlight';
}

input.onblur = function() {
  this.className = '';
}

回答by Miltos Kokkonidis

Setting a handler for the blur event using vanilla Javascript:

使用 vanilla Javascript 为模糊事件设置处理程序:

You could set the blur event's handler for the specific element "test" in vanilla jQuery using code such as this

您可以使用如下代码在 vanilla jQuery 中为特定元素“test”设置模糊事件的处理程序

document.getElementById("test").onblur= yourEventHandler

You can use the event handler in your question without any modifications. That's that part covered. However, I believe there is more to be said here.

您可以在问题中使用事件处理程序,无需任何修改。这就是覆盖的那部分。不过,我相信这里还有更多要说的。



The big picture:

大图:

The blur/focus events on text inputs are among the least troublesome events to work with in terms of compatibility across browsers. But if you are going to do any serious development I recommend using a framework such as jQuery, YUI, Dojo, MooTools etc. These will both help you write nicer code and will shield you from compatibility problems.

就跨浏览器的兼容性而言,文本输入上的模糊/焦点事件是最不麻烦的事件之一。但是,如果您打算进行任何严肃的开发,我建议您使用诸如 jQuery、YUI、Dojo、MooTools 等框架。这些都将帮助您编写更好的代码并保护您免受兼容性问题的影响。

Unfortunately, the reality web developers have to face is that of many browsers with similar, but not identical behaviours. It is not enough to find a solution that happensto work on a browser we happen to be using at the moment we test the piece of code we have just written. We need to ensure our code works correctly across all browsers our application is targetting. So what happens if you suddenly discover that your way of assigning the blur even does not work on some browser for some specific element but another one does? Do you go everywhere in your code and put if's there? Are you sure you haven't missed anything if you go this route? And then, if you find another problem with another browser do you add another if' and so on and so forth? Maybe you decide to define a function setBlurEventHandlerthat does what it says on the box and use it everywhere in your code instead of statements such as the above. Do you do that just for the blur event or for pretty much everything you do? It makes sense to do it for other things too. Great. You now have a framework for writting code that is compatible across browsers. If all of us kept our frameworks to ourselves we would be spending a lot of time re-discovering and fixing the same problems. Enter open-source Javascript frameworks. You can just use them taking advantage of the hours of hard labour others put into them, but you can also contribute by reporting bugs, writing code and documentation. Doesn't this make more sense? (Or if at some point in the future you are sure you have a framework based on some very clever ideas, however incomplete, by all means put it out there and see both what you can offer to the community and what the community can do for you ... )

不幸的是,Web 开发人员必须面对的现实是许多浏览器具有相似但不完全相同的行为。在我们测试刚刚编写的代码段时,仅仅找到一个恰好适用于我们正在使用的浏览器的解决方案是不够的。我们需要确保我们的代码在我们的应用程序所针对的所有浏览器上都能正常工作。那么,如果您突然发现您分配模糊的方式在某些浏览器上对某些特定元素不起作用,但在另一种浏览器上起作用,会发生什么?你是否在代码中到处走,然后把 if 放在那里?如果你走这条路,你确定你没有错过任何东西吗?然后,如果您发现另一个浏览器的另一个问题,您是否添加另一个 if' 等等?也许你决定定义一个函数setBlurEventHandler它按照盒子上的说明执行,并在代码中的任何地方使用它,而不是像上面那样的语句。你只是为了模糊事件还是为了你所做的几乎所有事情?为其他事情做这件事也很有意义。伟大的。您现在拥有了一个编写跨浏览器兼容的代码的框架。如果我们所有人都保留自己的框架,我们将花费大量时间重新发现和修复相同的问题。进入开源 Javascript 框架。您可以利用其他人投入的辛勤劳动来使用它们,但您也可以通过报告错误、编写代码和文档来做出贡献。这不是更有意义吗?(或者,如果在未来的某个时候你确定你有一个基于一些非常聪明的想法的框架,无论多么不完整,

To better drive this point home, let me show you some comments taken from jQuery's source. As I said before, the blur/focus events on text inputs are among the least troublesome events to work with in terms of compatibility across browsers. But how confident are you that you are aware (or remember!) the various browser peculiarities your code has to deal with when the handling of even the most basic and least troublesome events comes with such inline code documentation?

为了更好地说明这一点,让我向您展示一些取自 jQuery 源代码的评论。正如我之前所说,就跨浏览器的兼容性而言,文本输入上的模糊/焦点事件是最不麻烦的事件之一。但是,当处理最基本和最不麻烦的事件时,您是否有信心知道(或记住!)您的代码必须处理的各种浏览器特性?

// IE<9 dies on focus/blur to hidden element (#1486)

// IE doesn't fire change on a check/radio until blur; trigger it on click

// This still fires onchange a second time for check/radio after blur.

For the reasons outlined above I recomment against working with the DOM directly.

由于上述原因,我建议不要直接使用 DOM。



A better approach using jQuery:

使用 jQuery 的更好方法:

Suppose you had a divcalled formDivwith three inputelements only one of which initially had the editInputclass.

假设您有一个包含三个元素的div调用formDiv,其中input只有一个最初具有editInput该类。

<div id=formDiv>     
    <input type="text" name="test1" id="test1" />   
    <input type="text" name="test2" id="test2" class='editInput' />    
    <input type="text" name="test3" id="test3" />           
</div>

Using jQuery, you could simply do something like (I copied the actual logic of the event handler from your code):

使用 jQuery,您可以简单地执行以下操作(我从您的代码中复制了事件处理程序的实际逻辑):

("#formDiv input").blur(function(){ 
      if(this.className=='editInput'){
          doStuff(this.target);
      }
 });

which I believe is closer to what you wanted to do, than other solutions here. (In your code you were trying to attach the event to the div containing the inputs. I may have misinterpreted your intentions but I thought this was what you wanted.)

我相信这比这里的其他解决方案更接近您想要做的事情。(在您的代码中,您试图将事件附加到包含输入的 div。我可能误解了您的意图,但我认为这就是您想要的。)

You can try this solution with this jsFiddle: http://jsfiddle.net/r7tuT/3/

您可以使用此 jsFiddle 尝试此解决方案:http: //jsfiddle.net/r7tuT/3/



Some parting thoughts:

一些离别感想:

There are people that will tell you that this or that framework is better and they may be right. I will only comment that jQuery is the most popular one and is pretty decent. The choice is yours, but as I said I believe you should start using one of these frameworks sooner than later as it will improve the quality of your work, let you do certain things in a blink of an eye and change the way you approach problems. When a framework or programming language does this to you, is a great moment in your life as a coder :-)

有些人会告诉你这个或那个框架更好,他们可能是对的。我只会评论 jQuery 是最受欢迎的,而且相当不错。选择是你的,但正如我所说,我相信你应该尽早开始使用这些框架中的一个,因为它会提高你的工作质量,让你在眨眼间完成某些事情并改变你处理问题的方式. 当框架或编程语言对您这样做时,这是您作为编码员生活中的一个美好时刻:-)

回答by ose

Try onblurinstead of blur.

尝试onblur代替blur.

bluris a method which causes an object to lose focus, whereas onbluris an event that is raised when the object loses focus.

blur是导致对象失去焦点的方法,而onblur是当对象失去焦点时引发的事件。