Web API

Using hidden file input elements using the click() method

You can hide the admittedly ugly file <input> element and present your own interface for opening the file picker and displaying which file or files the user has selected. You can do this by styling the input element with display:none and calling the click() method on the <input> element.

Consider this HTML:

<input type="file" id="fileElem" multiple accept="image/*" style="display:none">
<button id="fileSelect">Select some files</button>

The code that handles the click event can look like this:

const fileSelect = document.getElementById("fileSelect"),
  fileElem = document.getElementById("fileElem");

fileSelect.addEventListener("click", function (e) {
  if (fileElem) {
    fileElem.click();
  }
}, false);

You can style the new button for opening the file picker as you wish.

隐藏 file input 元素

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Using hidden file input elements using the click() method</title>
    </head>
    <body>
        <input type="file" id="fileElem" multiple accept="image/*" style="display:none">
        <button id="fileSelect">Select some files</button>

        <script type="text/javascript">
            const fileSelect = document.getElementById("fileSelect"),
                fileElem = document.getElementById("fileElem");

            fileSelect.addEventListener("click", function(e) {
                if (fileElem) {
                    fileElem.click();
                }
            }, false);
        </script>
    </body>
</html>

参考

Using hidden file input elements using the click() method

原文地址:https://www.cnblogs.com/Satu/p/14643351.html