如何通过js如何打开input?

一个按钮一个input

<button>Upload</button>
<input type="file" multiple>

点击input会弹出上传文件窗口
但是我想要的效果:点击button会弹出input上传窗口,这个用js该怎么实现呢?

阅读 4.9k
7 个回答
$("button").on("click",function () {
        $("input").click()
    })

input opactity设置为0后绝对定为到button上面试试

定制文件输入框(input,type,file)样式

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>三十客-定制文件输入框(input,type,file)样式</title>
    <style>
        .file-wrapper {
            position: relative;
            width: 225px;
        }
        .file-label {
            display: block;
            padding: 14px 20px;
            background: #39D2B4;
            color: #fff;
            font-size: 1em;
            text-align: center;
            transition: all .4s;
            cursor: pointer;
        }
        .input-file {
            position: absolute;
            top: 0; left: 0;
            width: 225px;
            opacity: 0;
            padding: 14px 0;
            cursor: pointer;
        }
        .input-file:hover + .file-label,
        .input-file:focus + .file-label {
            background: #34495E;
            color: #39D2B4;
        }
        form {
            padding: 1rem 0 0 1rem;
        }
    </style>
</head>
<body>
<h2>点击按钮查看演示效果</h2>    
<form action="#">
    <div class="file-wrapper">
        <input class="input-file" id="my-file" type="file">
        <label tabindex="0" for="my-file" class="file-label">选择一个文件...</label>
    </div>
</form>
</body>
</html>

button,input 自己通过id 或者 tag 获取,大致写法如下

button.onclick=function(){
    input.onclick();
}

如果buttoninput[type=file]都要显示出来,那么在button的点击事件中用input.click()触发选择文件窗口;
如果仅需要显示button,那么可以将input[type=file]绝对定位移到button的上面,并将input[type=file]的透明度设为0,这样就只会显示button,而点击button时实际上点击的时input[type=file]

点击button的时候执行input的点击事件就行了。如果不想显示input file的话,那就调整它的透明度就行。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id="btn">按键</button>
    <input type="file" id="file">

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script>
        $("#btn").click(function(){
            $("#file").click();
        })
    </script>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题