简体   繁体   English

包装 div 上的 Javascript 模糊事件

[英]Javascript blur event on wrapper div

I have inner input field and a wrapper div element.我有内部输入字段和一个包装 div 元素。 I have added contenteditable attribute to the div element in order to be able to set focus on it.我已经向 div 元素添加了contenteditable属性,以便能够将焦点设置在它上面。 I would like to catch the onblur event of the div .我想捕捉divonblur 事件

Now, If I'm in focus on the input field and click with the mouse on different place in the screen the blur event of the input field is called of course but not the blur event on the div.现在,如果我专注于输入字段并用鼠标单击屏幕的不同位置,输入字段的模糊事件当然会被调用,但不会调用 div 上的模糊事件。 Of course this makes sense - this is how the browser works.当然这是有道理的——这就是浏览器的工作方式。

But anyway, I was wondering if and how it is possible to achieve that.但无论如何,我想知道是否以及如何实现这一目标。

  <div id="wrapperDiv" contenteditable class="wrapperDivClass">
      <input id="innerId">
  </div>

For blur event to fire on an element, the element needs to receive focus first.要在元素上触发模糊事件,该元素需要首先接收焦点。 But elements do not receive focus by default.但是默认情况下元素不会获得焦点。

You can add tabindex="0" or contentEditable to your div so it will receive focus.您可以将tabindex="0"contentEditable到您的 div 中,以便它获得焦点。

See it in action: http://jsfiddle.net/t25rm/看到它在行动: http : //jsfiddle.net/t25rm/

Answered here: Div - onblur function在这里回答: Div - onblur 功能

Issue solved when I changed the blur event to focusout将模糊事件更改为focusout时问题已解决

From MDN web docs: The focusout event is fired when an element is about to lose focus.来自 MDN 网络文档:当元素即将失去焦点时会触发 focusout 事件。 The main difference between this event and blur is that the latter doesn't bubble.此事件与模糊之间的主要区别在于后者不会冒泡。

This is exactly what I needed.这正是我所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM