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 l开发者_如何学Pythonost focus and other has taken focus).
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. When 'foo' loses focus I should hide element '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.
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.
The Blur handler sets up a 1/2 second timeout which will call SomeFunction()
. The Focus handler cancels the timeout to prevent the function call. 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.
精彩评论