为了保证不同浏览器下的UI一致我们有需求要自定义input type=”file”元素的样式
1. 隐藏input type=”file”
2. 用CSS将a+span做成按钮样式,对其做事件绑定,点击之后触发input type=”file”的点击事件
3. 用input type=”text”显示input type=”file”选中文件的值
HTML
<input type="image" id="album_img" src="/image/album_default.png">
<input id="album_file" type="file" title="选择发送图片" style="visibility: hidden" />
CSS
input[type='image']{
width:auto;
height:auto;
max-width:80%;
max-height:80%;
margin: 5px;
vertical-align: middle;
background:#f4f4f4;
cursor: pointer;
padding: 9px;
border-radius:3px;
border: 1px solid #c6c6c6;
outline:none;
}
input[type='image']:hover {
background-color: #e1e1e1;
}
input[type='image']:active {
background-color: #c6c6c6;
}
JavaScript
$(function() { $('#album_img').click(function(event) { event.preventDefault(); $('#album_file').trigger('click'); }); //this works for FF, easy job $('#album_file').bind('change', function() { changeFile(albumfileInput.id); }); }); var changeFile = function (controlId) { var path = getControl(controlId).value; var suffixIndex = path.lastIndexOf('.'); if (suffixIndex != -1 && path.length > suffixIndex) { var pathSuffix = path.substring(suffixIndex + 1, path.length); if (null != pathSuffix && (pathSuffix.toLowerCase() == 'png' || pathSuffix.toLowerCase() == 'jpg' || pathSuffix.toLowerCase() == 'jpeg' ) ) { window.console.info('图片上传代码'); } else { window.console.info('请选择常用的图片格式(png/jpg/jpeg)'); return; } } else if (path === '') { return; } else { window.console.info('请选择正确的图片'); return; } }
问题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);
});
}
就是说IE不blur的话file不触发change事件,解决办法是设置一个setTimeout,然后再0毫秒后执行,利用文件选择框的阻塞。
本文介绍了如何通过CSS和JavaScript实现跨浏览器的input type="file"样式自定义,以达到一致的UI效果。通过隐藏原生input元素,使用a+span元素创建按钮样式,并绑定事件来触发文件选择。同时,讨论了Firefox不显示全路径以及IE不触发change事件的问题及解决方案。
6606

被折叠的 条评论
为什么被折叠?



