简体   繁体   English

是否可以推迟某些javascript函数的执行,直到浏览器事件得到完全处理?

[英]Is it possible to postpone execution of some javascript function until browser event is fully processed?

For example I need to execute some function when onblur/onfocus event is processed (one element has lost focus and other has taken focus). 例如,当处理onblur / onfocus事件时,我需要执行一些功能(一个元素失去焦点,另一个元素获得焦点)。

To be more specific I have something like the following. 更具体地说,我有类似以下内容。

<div id="foo" tabIndex="1" onblur="document.getElementById('bar').style.display = 'none';">foo</div>
<div id="bar" tabIndex="2" onclick="alert('bar');">bar</div>
<div>stuff</div>

Let's suppose element 'foo' is focused. 让我们假设元素“ foo”是集中的。 When 'foo' loses focus I should hide element 'bar'. 当“ foo”失去焦点时,我应该隐藏元素“ bar”。 But if I click on 'bar' I should see alert. 但是,如果我单击“栏”,则应该看到警报。 It doesn't work because after event onblur is processed then element 'bar' is invisible, and neither onclick nor onfocus occur. 它不起作用,因为在处理事件onblur之后,元素“ bar”不可见,并且onclick和onfocus都不会发生。

Just manage it in your code. 只需在您的代码中进行管理即可。

<script type="text/javascript">
var blurTimeout;
function Blur(el)
{
    blurTimeout = setTimeout(function() 
    {
        SomeFunction();
    }, 500);
}
function Focus(el)
{
    if (blurTimeout)
        cancelTimeout(blurTimeout);
}
</script>
<input id="input1" type="text" onblur="Blur(this);" />
<input id="input2" type="text" onfocus="Focus(this);" />

EDIT: 编辑:

Updated. 更新。 Now you need only attach the Focus handler to one element. 现在,您只需要将Focus处理程序附加到一个元素。

The Blur handler sets up a 1/2 second timeout which will call SomeFunction() . 模糊处理程序设置一个1/2秒的超时时间,该超时时间将调用SomeFunction() The Focus handler cancels the timeout to prevent the function call. Focus处理程序取消超时以防止函数调用。 You can adjust the delay to make it appear more immediate, but given your requirement, it must be asynchronous. 您可以调整延迟以使其看起来更即时,但是根据您的要求,它必须是异步的。

This is a rather kludgy solution. 这是一个相当笨拙的解决方案。 If I found myself writing this in production code, I would rethink the design or (if possible) revisit the requirements. 如果发现自己是在生产代码中编写的,那么我将重新考虑设计或(如果可能)重新考虑需求。

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

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