原生的<input type="file">
标签在Firefox下显示是这样的:

而在chrome显示是这样的:

其中的选择文件的按钮和后面文字是一体的,点击后面的文字同样可以进行文件选择,这是原生<input type="file">
标签显示的结果。
有些人想自定义显示按钮上的文字,或者 自定义 后面显示的文字,又或者不想让用户点击文字就可以上传文件,等等。
自定义样式实现思路
隐藏<input type="file">
,自己写一个按钮,加上onclick事件,触发file文件域。
具体做法如下:
- 页面上放个隐藏的
<input type="file">
; - 然后加上一个文本
<a id="filename">请选择文件</a>
用于显示文件名和一个按钮input(type="button") - 点按钮的时候调用
<input type="file">
的click选择文件 - 在
<input type="file">
的onchange事件中把其值显示在文本<a>
中
实现代码
页面显示部分
<form id='mainForm' action="xxx.action" method="post" name="mainForm">
<input type="button" value="选择文件" onclick="document.mainForm.excel.click()">
<a id="filename">请选择文件</a>
<input type="file" name="excel" id="excel" accept="application/vnd.ms-excel" style="display:none" onChange="changeText(this)">
</form>
js代码处理
function changeText(th){
var filename = document.getElementById("filename");
var exist = th.value.lastIndexOf("\\");
// 火狐浏览器直接可以获取到文件名
if(exist == -1){
filename.textContent = th.value;
}
//chrome或获取到绝对路径
else{
filename.textContent = th.value.substring(exist + 1);
}
}
注意事项
刚开始考虑如何在选择文件后将文件名显示在按钮后面时,考虑的是使用innerText
方法,将读取的文件名塞到<a>
标签内。但是发现innerText
方法在Firefox下不起作用。在网上查了相关资料后发现innerText
方法并非W3C标准属性,因此我们无法在FireFox中使用它,一般情况下我们可以使用textContent
来代替。具体的区别可以参考文章:被玩坏的innerHTML、innerText、textContent和value属性
如果觉得有用,欢迎关注我的微信,有问题可以直接交流:

网友评论