自定义input[type="file"]的样式

php中文网
发布: 2016-09-27 14:05:24
原创
1487人浏览过

input[type="file"]的样式在各个浏览器中的表现不尽相同:

1. chrome:


 

2. firefox:

 


3. opera:


4. ie:


5. edge:


另外,当我们规定 input[type="file"] 的高度,并把它的行高设置成与其高度相等后,chrome中难看的样式出现了:


“未选择任何文件”这一行并没有竖直居中。

壁纸样机神器
壁纸样机神器

免费壁纸样机生成

壁纸样机神器 0
查看详情 壁纸样机神器

似乎在 firefox 中好看一些,嗯,我比较喜欢用 firefox。但是这些浏览器中的表现不一致,我们必须做兼容处理。

思路:

1. 自定义与其中一个浏览器表现类似的样式,将其放在下层;

2. 将浏览器本身的表现出来的样式“隐藏掉”, opacity:  0; 置于上层,这样我们点击的才是 input[type="file"] 响应的事件;

3. 选择文件或改变文件后,改变显示 file 的值。

代码:

html:
<form action="" class="activityForm">
  <div class="file">
	<label for="file">文件:</label>
	<div class="userdefined-file">
	  <input type="text" name="userdefinedFile" id="userdefinedFile" value="未选择任何文件">
	  <button type="button">上传</button>
	</div>
	<input type="file" name="file" id="file">			
  </div>
</form>
登录后复制
css: 
.file {
  position: relative;
  height: 40px;
  line-height: 40px;
}
.file label {
  display: inline-block;
}
.userdefined-file {
  position: absolute;
  top: 0;
  left: 60px;
  z-index: 2;
  width: 300px;
  height: 40px;
  line-height: 40px;
  font-size: 0;  /*应对子元素为 inline-block 引起的外边距*/
}
.userdefined-file input[type="text"] {
  display: inline-block;
  vertical-align: middle;
  padding-right: 14px;
  padding-left: 14px;
  width: 220px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.userdefined-file button {
  display: inline-block;
  vertical-align: middle;
  width: 80px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  background-color: #f54;
  border: none;
  color: #fff;
  cursor: pointer;
}
.file input[type="file"] {
  position: absolute;
  top: 0;
  left: 60px;
  z-index: 3;
  opacity: 0;
  width: 300px;
  height: 40px;
  line-height: 40px;
  cursor: pointer;
}
登录后复制
js:
document.getElementById("file").onchange = function() {
    document.getElementById("userdefinedFile").value = document.getElementById("file").value;
}
登录后复制

这样处理后,就在各个浏览器中表现一致了:

1. 未选择任何文件时,在 chrome 中:


2. 在选择文件后,在 firefox 中:

  

 

  

 

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号