首页 > 解决方案 > 如何使图像表现得像文件输入?

问题描述

当点击默认照片时,它应该让用户从他的计算机中选择一个文件,而不是让input type = "file"用户首先点击浏览按钮而不是选择一个文件。用户应直接单击默认照片,并应出现文件选择窗口。

<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".

我应该如何使这个功能工作?这是我的默认图像:

在此处输入图像描述

标签: javascripthtmlcssfunctionclick

解决方案


要使image行为类似于输入元素file,您只需在单击.input.click()img

这应该是你的代码:

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

演示:

<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>

笔记:

你只需要使用document.getElementById("file")它来访问一个元素id


推荐阅读