跨浏览器样式“选择文件”;按钮

Cross browser styling "choose file" button

本文关键字:选择文件 按钮 文件 选择 浏览器 样式      更新时间:2023-09-26

这是我的代码:

html:

<form>
    <input id = "file" type="file" />
    <div id="custom_button">custom button</div>
</form>
Jquery:

$("#custom_button").on("click", function () {
    $("#file").click();    
});
css:

#file {
    display: none;
}

但这只适用于firefox和chrome,在safari和opera中,在点击custom button时,文件选择窗口没有调用

演示:http://jsfiddle.net/J4GdN/

问题:为什么这在safari和opera中不起作用?在这些浏览器中有什么替代方案?

一些用户代理不允许通过js触发点击输入文件元素,特别是在css display:none中。另一种方法是:

HTML

<input id="file-element" type="file" name="my-file-upload" />
<div id="file-element-replacement">
    <input type="text" value="" />
    <img alt="custom upload" src="custom-upload.png" />
</div>
CSS

#file-element {
    /* if opacity is 0 => some UAs interpret it like display:none */
    filter: alpha(opacity=1);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=1);
    -moz-opacity: 0.01;
    -webkit-opacity: 0.01;
    opacity: 0.01;
    position: relative;
    z-index: 2;
}
#file-element-replacement {
    position: relative;
    top: -20px;
    z-index: 1;
}

将input-file设置为透明,并在后面添加input-text + image作为图层进行模拟。

另一个选择是使用标准的<label>标记,将for属性设置为<input>id

你可以根据需要隐藏<input><label>的样式。

在我的测试中,这在不同浏览器中都能很好地工作,因为它是标准功能。