首页 > 代码库 > 文件上传按钮的用户自定义样式的实现

文件上传按钮的用户自定义样式的实现

一般在做 WEB 开发项目的时候碰到文件上传必不可少,但是因为各家浏览器对于

<input type="file">

标签支持不同所以在各个浏览器下的显示也是不一样的。可能在用户体验方面会形成困扰,今天就给大家介绍一下文件上传按钮的用户自定义样式的实现。

 

实现原理:

建立两个层,一个层包装 <input type="file"> 以下简称文件按钮层,一个层包装上传文件按钮的自定义样式,以下渐层样式层。设置两个层的大小一致,将文件按钮层设置相对定位 position = relative、z-index = 2,将样式层设置为绝对定位设置 position=absolute、z-index = 1 并且设置 top left 属性使之与文件按钮层重叠。这样就使大小的一样的两个层重叠在了一起,并且文件按钮层在上面。接下来设置文件按钮层为完全透明,便实现了用户自定义样式。

下面给出实现代码,以下代码可以直接拖动至浏览器查看效果,建议使用 chrome 浏览器。IE 浏览器对于CSS 样式支持不够,不能够显示渐变效果。

 

代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3   <head> 4     <title>hidetypebutton.html</title> 5     <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 6       7     <!--<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">--> 8         <!-- 实现 type = "file" 的 input 文件上传按钮的自定义样式--> 9         <style type="text/css">10             .user-file-outwrap{width: 100px;height: 30px;overflow: hidden;position: relative;border: 1px solid gainsboro;border: 1px solid rgba(0,0,0,0.1) !important;}11             .user-file-wrap{width: 100%;height: 100%;overflow: hidden;position: relative;z-index: 2;overflow: hidden;}12             .user-file-wrap input{margin: 0 0 0 -2px;padding: 0;width: 100%;height: 100%;opacity: 0;filter: alpha(opacity=0);cursor: pointer;}13             .user-file-bg{14                 width: 100%;height: 100%;position: absolute;top: -1px;left: -1px;z-index: 1;text-align: center;font-size: 12px;line-height: 30px;15                 background-color: transparent;16                 background-image: -moz-linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));17                 background-image: -o-linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));18                 background-image: -webkit-gradient(linear,left top,left bottom,from(rgba(255, 255, 255, .85)),to(rgba(247, 247, 247, .85)));19                 background-image: -webkit-linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));20                 background-image: linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));21                 border: 1px solid gainsboro;border: 1px solid rgba(0,0,0,0.1) !important;22                 color: #444;23             }24              25              26         </style>27   </head>28    29   <body>30     <div class="user-file-outwrap">31         <div class="user-file-wrap"><input type="file" class="file"></div>32         <div class="user-file-bg">点击上传</div>33     </div>34     <br/>35     <div><strong>在 IE 浏览器下没有渐变效果并且文件上传可能需要双击才能触发效果</strong></div>36   </body>37   <input type="file">38 </html>