How to make photo to function as <input type =

2019-05-29 08:01发布

问题:

When the default photo is clicked it should make a user to select a file from his computer other than making an input type = "file" that makes the user to first click on browse button than select a file. A user should directly click on default photo and a file selection window should appear.

<html lang = "en">
    <head>
        <title>
            Profile Click
        </title>
        <style>
            #file{
                display: none;
            }
        </style>
    </head>
    <body>
        <script>
            function pro1(){
                document.prolis.getElementById("image") = document.prolis.getElementById("file");
            }
        </script>
        <form name = "prolis">
        <img src = "index.jpg" id = "image" onclick = "pro1()";>
        <input type = "file" id = "file">
    </body>
</html>
Mozilla Firefox console shows "TypeError: document.prolis.getElementById is not a function".

How should I make this function work? This is my default image:

回答1:

To make the image behave like an input file element, you can just call the input file .click() method when you click on the img.

This is how should be your code:

function pro1(){
   document.getElementById("file").click();
}

Demo:

<html lang = "en">
    <head>
        <title>
            Profile Click
        </title>
        <style>
            #file{
                display: none;
            }
        </style>
    </head>
    <body>
        <script>
            function pro1(){
                document.getElementById("file").click();
            }
        </script>
        <form name = "prolis">
        <img src = "index.jpg" id = "image" onclick = "pro1()";>
        <input type = "file" id = "file">
    </body>
</html>

Note:

You just need to use document.getElementById("file") to access an element by its id.



回答2:

if you want to select element by id you should do it like this:

document.getElementById('element_id')

If you want to select form element you should do it like this:

document.form_name.element_id


回答3:

Create a click event for #file in your function

function pro1(e){
 e.preventDefault();
    document.getElementById('file')[0].click();
    });
  }