简体   繁体   English

onBlur 事件阻止 onClick 事件

[英]onBlur event prevents onClick event

I have an input text box with an onfocus and an onblur event.我有一个带有 onfocus 和 onblur 事件的输入文本框。 Under the text box is a div which is hidden by with display: none.文本框下方是一个 div,由 display: none 隐藏。

The div should be displayed if text box is focused and hide if blurred.如果文本框聚焦,则应显示 div,如果模糊则隐藏。 This seem to work.这似乎有效。 Now I want to let the div stay visible or do any clicks on div if I click on div (or one of its contents) itself.现在,如果我单击 div(或其内容之一)本身,我想让 div 保持可见或对 div 进行任何单击。 This doesn't work.这不起作用。 The onBlur event prevents any events on the div. onBlur 事件阻止了 div 上的任何事件。 I already tried to identify which new element was clicked but can't find any attribute which helps me.我已经尝试确定单击了哪个新元素,但找不到任何对我有帮助的属性。 relatedTarget is NULL.相关目标为 NULL。 At this time the only solution seems for me to add a onfocus on every other node besides the div and its children此时对我来说唯一的解决方案似乎是在除 div 及其子节点之外的每个其他节点上添加一个焦点

Do you have any other ideas than this?除了这个你还有别的想法吗? Thank you for your help.感谢您的帮助。

Jens延斯

When onblur runs it will hide the div so when the click is going to be made it will not fired on div because the div is invisible.当 onblur 运行时,它将隐藏 div,因此当要进行点击时,它不会在 div 上触发,因为 div 是不可见的。 so :所以 :

 // use the following global variable
   var mytimer = null;
  
  function newOnBlur()
  {
     mytimer = setTimeout(YourCurrentOnBlurFunctionWihoutParentheses,150);
  }
  
  // clearTimeout in the first line of your click function
  function newOnClick()
  {
     clearTimeout(mytimer);
     //  rest of your click event
  }

Thank you all for your answers.谢谢大家的答案。 I will take nAviDs suggestion.我会接受 nAviDs 的建议。 Seems a little ugly with global variable but it seems the only way to do this.使用全局变量似乎有点难看,但这似乎是唯一的方法。

For those who have the same problem: setTimeout is a little pedantic in my case.对于那些有同样问题的人:在我的情况下,setTimeout 有点迂腐。 I had to set it in this way or timeout is never used:我必须以这种方式设置它,否则永远不会使用超时:

var timer = null;
function timer_function(divname)
{
    timer = setTimeout(function(){document.getElementById(divname).style.display='none'}, 200);
}

I had to refocus to text box, if timeout gets cleared otherwise blur function is not working anymore.如果超时被清除,我不得不重新聚焦到文本框,否则模糊功能将不再起作用。

Thank you for your time and help.感谢您的时间和帮助。 :) :)

onmousedown active before onblur onmousedownonblur之前激活

div.addEventListener('mousedown', function(event) {
   event.preventDefault();
   event.stopPropagation();
});

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

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