http://www.itfeed.cn/post.asp?id=3420
因为不同浏览器下如果使用默认的input type=”file”元素,效果如下
为了保证不同浏览器下的UI一致我们有需求要自定义input type=”file”元素的样式
如何Style input type=”file”元素的相关长篇讨论
1. Styling an input type=”file”
http://www.quirksmode.org/dom/inputfile.html
2. Howto Style the Button of a input type=”file” Control
http://imar.spaanjaars.com/154/howto-style-the-button-of-a-input-typefile-control
翻译成白话文就是
1. 隐藏input type=”file”
2. 用CSS将a+span做成按钮样式,对其做事件绑定,点击之后触发input type=”file”的点击事件
3. 用input type=”text”显示input type=”file”选中文件的值
查看能工作的live code
http://jsfiddle.net/jihao/sFCQV/
HTML
<input type="text" id="fakeFile" name="fakeFile"> <a class="linkButton" id="link_browse" href="#"><span>Link Button BROWSE</span></a> <input id="theFile" type="file" style="visibility:hidden;opacity:0;cursor:pointer;*filter: alpha(opacity=0);">
CSS
a.linkButton{
background: #332233;/*style this link to look like a button*/
color: #FFFFFF;
padding: 0 0 0 10px;
text-decoration: none;
}
a.linkButton>span{
padding: 0 10px 0 0;
}
JavaScript
$(function() { $('#browse,#link_browse').click(function(event) { event.preventDefault(); $('#theFile').trigger('click'); }); function changeCallBack() { $('#fakeFile').val($('#theFile').val()); }; //this works for FF, easy job $('#theFile').bind('change', function() { alert('gotcha!'); changeCallBack(); }); });
写完这段代码之后遇到的相关问题
问题1. FireFox下不会显示文件全路径(google得知这是FF的安全考虑,不影响form提交)
问题2. IE下选择文件后不会触发change事件,原因是IE处理打开文件的机制(参考下面的链接看更多讨论)
对于IE8,这个问题的解决办法如下,setTimeout会阻塞,直到文件选择器关闭之后,回调函数才被调用(更新用来显示的input type=”text”的值)
if ($.browser.msie) { $('#theFile').bind('click', function() { //this solution works for IE8, not Maxthon2, so seems not IE6 either(not tested) setTimeout(function() { alert('[IE8] setTimeout get called after open file dialog was closed'); changeCallBack(); }, 0); }); }
查看能工作的live code
http://jsfiddle.net/jihao/sFCQV/
关于IE change事件的相关讨论
1. jQuery, .change() notification, and IE (关于radio button的change事件绑定)
http://norman.walsh.name/2009/03/24/jQueryIE
2. jQuery: change event to input file on IE
http://stackoverflow.com/questions/2389341/jquery-change-event-to-input-file-on-ie
就是说IE不blur的话file不触发change事件,解决办法是设置一个setTimeout,然后再0毫秒后执行,利用文件选择框的阻塞。