没有输入字段的文件上传按钮?

Pau*_*aul 23 html css jquery file-upload

可能重复:
jQuery:模拟点击<input type ="file"/>在Firefox中不起作用?

默认情况下,是否可以在其旁边没有输入的文件按钮?理想情况下,我想要的是一个按钮,让用户可以导航到文件而不显示他们在上传之前选择的内容.在用户选择文件后,我将通过以下内容提交表单:

$("#file").change(function() {
    $("#update_button").trigger('click');
});
Run Code Online (Sandbox Code Playgroud)

我确信这一定是可能的,有些css或jquery魔法......

Jos*_*ber 52

你可以简单地隐藏input按钮visibility: hidden;,并将click事件处理程序附加到另一个按钮:

HTML:

<input type="file" name="somename" size="chars">
<button>Choose File</button>
Run Code Online (Sandbox Code Playgroud)

CSS:

input {
    display: block;
    visibility: hidden;
    width: 0;
    height: 0;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

$('button').click(function(){
    $('input').click();
});
Run Code Online (Sandbox Code Playgroud)

这是小提琴:http://jsfiddle.net/tCzuh/


Mat*_*nen 22

如果我没有记错,HTML5允许你调用click一个隐藏的输入元素法通过自定义按钮(为什么不让它没有一个元素的工作,我不知道)来显示文件对话框.不幸的是,并非所有当前使用的浏览器都支持这种功能,因此您不得不将文件输入样式设置为按钮.

这是一个非常丑陋但很巧妙的CSS黑客,我曾在网站上遇到过一次(可能是imgur):

.fileupload {
    width: 100px;
    height: 50px;
    position: relative;
    overflow: hidden;
    background: ...; /* and other things to make it pretty */
}

.fileupload input {
    position: absolute;
    top: 0;
    right: 0; /* not left, because only the right part of the input seems to
                 be clickable in some browser I can't remember */
    cursor: pointer;
    opacity: 0.0;
    filter: alpha(opacity=0); /* and all the other old opacity stuff you
                                 want to support */
    font-size: 300px; /* wtf, but apparently the most reliable way to make
                         a large part of the input clickable in most browsers */
    height: 200px;
}
Run Code Online (Sandbox Code Playgroud)

和它一起使用的HTML:

<div class="fileupload">
  <input type="file" />
  Any content here, perhaps button text
</div>
Run Code Online (Sandbox Code Playgroud)

它的作用是使文件输入本身巨大(通过改变字体大小(!?))以确保它覆盖按钮,然后切断多余的overflow: hidden;.这可能不适用于绝对巨大的按钮.


小智 7

如果将不透明度设置为0,则可以在其下方添加另一个看起来像按钮的div.您可以按照自己喜欢的方式设置样式.

下面的工作代码示例:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<div class="wrapper">
    <div class="fakeuploadbutton">upload</div>
    <input id="file" type="file" name="file" />
</div>
<script type="text/javascript" charset="utf-8">
    jQuery('#file').css('opacity',0);    
</script>
<style type="text/css" media="screen">
    .wrapper { position: relative; }
    .fakeuploadbutton { 
        background: red url('myuploadbutton.png') no-repeat top left;
        width: 100px; height: 30px;
    }
    #file { 
        position: absolute;
        top: 0px; left: 0px; 
        width: 100px; height: 30px;
    }
</style>
Run Code Online (Sandbox Code Playgroud)

  • 这是跨浏览器兼容性问题的最佳方法. (2认同)