由于文件输入工作方式存在大量安全问题,因此很难修复。然而,有效的是这样的方案:
- 为文件输入设计自己的外观,在大小和形状上与默认文件输入相当接近
- 将您的文件输入和一个真实文件输入放在表单中的同一位置,真实的放在您的顶部
- 使真实输入透明(即,将不透明度设置为零)
现在点击您希望它们看起来的样式的元素实际上将被浏览器解释为点击文件输入。您必须对 IE 进行一些调整,因为 IE7 允许用户直接在输入中键入内容,而其他浏览器在任何地方单击元素时都会立即启动文件选择器。
edit — here 是一个至少可以在 Chrome 中运行的 jsfiddle。 HTML:
<div class='fancy-file'>
<div class='fancy-file-name'> </div>
<button class='fancy-file-button'>Browse...</button>
<div class='input-container'>
<input type='file'>
</div>
</div>
这包含了我将使用自己的 CSS 设置样式的“假”文件输入,以及真正的 <input> 元素。这是 CSS:
div.fancy-file {
position: relative;
overflow: hidden;
cursor: pointer;
}
div.fancy-file-name {
float: left;
border-radius: 3px;
background-color: #aaa;
box-shadow:
inset 1px 1px 3px #eee,
inset -1px -1px 3px #888,
1px 1px 3px #222;
font-weight: bold;
font-family: Courier New, fixed;
width: 155px;
font-size: 12px;
padding: 1px 4px;
}
button.fancy-file-button {
float: left;
border-radius: 3px;
border: 1px solid red;
background-color: #F5BD07;
font-weight: bold;
vertical-align: top;
margin: 0 0 0 3px;
}
div.input-container {
position: absolute;
top: 0; left: 0;
}
div.input-container input {
opacity: 0;
}
外部容器被制成“位置:相对”,以便将真实的<input>定位在假的东西上。假的东西有我虚构的花哨样式,它的大小与真实文件输入的整体大小差不多。真正的是绝对定位和透明的。
这里有一些 jQuery 来驱动它:
$('div.fancy-file input:file').bind('change blur', function() {
var $inp = $(this), fn;
fn = $inp.val();
if (/fakepath/.test(fn))
fn = fn.replace(/^.*\\/, '');
$inp.closest('.fancy-file').find('.fancy-file-name').text(fn);
});
浏览器不会为您提供完整的路径名,但会为您提供其中的一部分。一些浏览器(Chrome 和 IE)给你一个明显伪造的路径前缀,所以代码把它去掉了(因为它没用)。