How to make photo to function as <input type = “file”>?

你。 提交于 2019-12-10 11:42:39

问题


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();
    });
  }


来源:https://stackoverflow.com/questions/52334212/how-to-make-photo-to-function-as-input-type-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!