简体   繁体   中英

How to recognize that a file-input has opened a window

I have a function that runs when the user presses the esc button:

$(document).on('keyup', function (e) {
    if (e.keyCode == 27) {
        foo();
    }
});

I have a form with a file field.

<input type="file" />

When you click it, it opens a file-manager dialog, which can be closed with the esc as well. In that case, I want to avoid running the foo function. Is there a way to recognize it with javascript?

Here is some code that can do what you want (a complete test-page):

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>test-page</title>
 <script type="text/javascript">
//<!--
var ignr=false;

function func(e)
{ if(!ignr)
  { //add any key-specific tests here
    foo();
  }
  ignr = false;
  return;
}

function foo()
{
  return;
}

function func2(e)
{ //Could add a condition to do/not-do the next line, depending on the key...
  ignr = true;
  return;
}
// -->
 </script>
</head>
<body onkeyup="func(event);">
<input type="file" onkeyup="func2(event);" />
</body>
</html> 

The trick is to assign a different function to the input tag. This won't prevent the other function from being called, but the herein-specified func2() is called first, giving you the chance to set a flag-variable that can control what gets done in the "main" onkeyup function. Note while I didn't specify any tests for the Escape key, you can certainly add them, and even completely control which keys you want to allow "through" func2() to call foo() inside the main onkeyup function. At the moment, no keys pressed during the file-input will have any chance of calling foo() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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