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

通常在作 WEB 开发项目的时候碰到文件上传必不可少,可是由于各家浏览器对于 css

<input type="file"> html

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

 

实现原理: chrome

创建两个层,一个层包装 <input type="file"> 如下简称文件按钮层,一个层包装上传文件按钮的自定义样式,如下渐层样式层。设置两个层的大小一致,将文件按钮层设置相对定位 position = relativez-index = 2,将样式层设置为绝对定位设置 position=absolutez-index = 1 而且设置 top left 属性使之与文件按钮层重叠。这样就使大小的同样的两个层重叠在了一块儿,而且文件按钮层在上面。接下来设置文件按钮层为彻底透明,便实现了用户自定义样式。 浏览器

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

代码: ui

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>hidetypebutton.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
		<!-- 实现 type = "file" 的 input 文件上传按钮的自定义样式-->
		<style type="text/css">
			.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;}
			.user-file-wrap{width: 100%;height: 100%;overflow: hidden;position: relative;z-index: 2;overflow: hidden;}
			.user-file-wrap input{margin: 0 0 0 -2px;padding: 0;width: 100%;height: 100%;opacity: 0;filter: alpha(opacity=0);cursor: pointer;}
			.user-file-bg{
				width: 100%;height: 100%;position: absolute;top: -1px;left: -1px;z-index: 1;text-align: center;font-size: 12px;line-height: 30px;
				background-color: transparent;
				background-image: -moz-linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));
				background-image: -o-linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));
				background-image: -webkit-gradient(linear,left top,left bottom,from(rgba(255, 255, 255, .85)),to(rgba(247, 247, 247, .85)));
				background-image: -webkit-linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));
				background-image: linear-gradient(top,rgba(255, 255, 255, .85),rgba(247, 247, 247, .85));
				border: 1px solid gainsboro;border: 1px solid rgba(0,0,0,0.1) !important;
				color: #444;
			}
			
			
		</style>
  </head>
  
  <body>
  	<div class="user-file-outwrap">
  		<div class="user-file-wrap"><input type="file" class="file"></div>
  		<div class="user-file-bg">点击上传</div>
  	</div>
  	<br/>
  	<div><strong>在 IE 浏览器下没有渐变效果而且文件上传可能须要双击才能触发效果</strong></div>
  </body>
  <input type="file">
</html>
相关文章
相关标签/搜索