<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jquery美化input type=file文件上传表单字段</title> <style> .uploader { position:relative; display:inline-block; overflow:hidden; cursor:default; padding:0; -moz-box-shadow:0px 0px 5px #ddd; -webkit-box-shadow:0px 0px 5px #ddd; box-shadow:0px 0px 5px #ddd; -moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px; } .filename { float:left;display:inline-block; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; outline:0 none;cursor:default; text-overflow:ellipsis;white-space:nowrap; width:180px;height:32px;margin:0;padding:8px 10px;overflow:hidden; font-size:12px; border:1px solid;border-color:#ccc;border-right:0; -moz-border-radius:5px 0px 0px 5px; -webkit-border-radius:5px 0px 0px 5px; border-radius:5px 0px 0px 5px; text-shadow:1px 1px 0px #fff; color:#666; background:#f5f5f5; background:linear-gradient(#fafafa,#eee); -moz-box-shadow:0px 0px 1px #fff inset; -webkit-box-shadow:0px 0px 1px #fff inset; box-shadow:0px 0px 1px #fff inset; } .button { float:left;display:inline-block;height:32px;line-height:100%;margin:0;padding:8px 12px; outline:0 none;cursor:pointer; color:#333; text-shadow:1px 1px 0px #fff; border:1px solid #ccc; border-radius:0px 5px 5px 0px; box-shadow:0px 0px 1px #fff inset; background:#ddd; background:linear-gradient(#fff,#ddd); } .uploader:hover .button {background:#eee;background:linear-gradient(#ddd,#fff)} .uploader input[type=file] { /* 让file类型的元素透明度为0,覆盖在设计好的按钮上。 然后我们去点击设计好的按钮,实际上点击的是file元素。 */ position:absolute;top:0;right:0;bottom:0; border:0;padding:0;margin:0; height:32px; cursor:pointer; filter:alpha(opacity=0);opacity:0; } input[type=button]::-moz-focus-inner{padding:0;border:0 none;-moz-box-sizing:content-box;} input[type=button]::-webkit-focus-inner{padding:0;border:0 none;-webkit-box-sizing:content-box;} input[type=text]::-moz-focus-inner{padding:0;border:0 none;-moz-box-sizing:content-box;} input[type=text]::-webkit-focus-inner{padding:0;border:0 none;-webkit-box-sizing:content-box;} </style> </head> <body> <div class="uploader white"> <input type="text" class="filename" readonly="readonly"> <input type="button" class="button" value="浏览..."> <input type="file" name="userpicfile" size="30"> </div> </body> <!--加载jquery库文件--> <script type="text/javascript" src="jquery.js"></script> <script> $(function(){ //当file类型表单字段值改变时,同步更新text类型单行文本框的值。 $("input[type=file]").change(function(){ $(this).parents(".uploader").find(".filename").val($(this).val()); }); //模仿file类型表单字段的默认提示文本。 $("input[type=file]").each(function(){ if($(this).val()==""){ $(this).parents(".uploader").find(".filename").val("未选择文件"); } }); }); </script> </html>