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

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

1. chrome:

9d5a5f47aae80410d496529b004a89a0.png

2. firefox:

b647e64be7188674ba31ba305525394f.png

3. opera:

86acef69c9daebf29f39f17b109ff4aa.png

4. ie:

3fc033258327a7ae9d83b5aa84b3c09d.png

5. edge:

1c4d995e427fb15b6119c5060e401795.png

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

a4bc52a5e157b9b0f6a5f94cab3087a5.png

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

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

思路:

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

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

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

代码:

html:文件:

上传

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 中:

3345218527576de77511c018ef0e42ea.png

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

00d0681ceeab56db1f42593caf6d78c1.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值