问题说明
一般input[type=”file”]都不会采用默认样式,因此需要将真正起作用的隐藏掉,显示一个设计出的按钮样式。隐藏的方法有2种,一种是visibility:hidden,一种是opacity:0。visibility:hidden会给元素留有位置,但是通过点击无法触发事件。一般按钮上划上去时要添加cursor:pointer,但是在input[type=”file”]默认按钮上不会生效。
css解决方案
- 设置input[type=”file”]的font-size为0,这时,按钮在谷歌浏览器中就会变成一个19*6大小没有内容的方块,并不知道里面有什么撑起内容,如下图所示。
- 设置input[type=”file”]的宽高就可以得到一个可以触发选择文件的区域
- 在该区域下方设置按钮样式,因为上方透明,因此显示出下方样式,并给input添加cursor:pointer,因为19*6大小的区域仍残留input[type=”file”]默认按钮,该区域划上去不会有鼠标变小手的效果,因此,通过设置相对位置,将其移出按钮范围,并设置overflow:hidden。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.file {
display: flex;
width: 60px;
height: 30px;
background-color: blue;
overflow: hidden;
}
.file:hover {
background-color: red;
}
.file:active {
background-color: purple;
}
.file input {
width: 100%;
height: 40px;
position: relative;
top: -10px;
font-size: 0;
opacity: 0;
cursor: pointer;
}
</style>
</head>
<body>
<a href="javascript:;" class="file">
<input type="file">
</a>
</body>
</html>
js解决方案
也可以通过js实现相同功能,input按钮隐藏掉,通过显示的按钮上的点击事件触发input的选择文件事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.file {
display: flex;
width: 60px;
height: 30px;
background-color: blue;
overflow: hidden;
}
.file:hover {
background-color: red;
}
.file:active {
background-color: purple;
}
.file input {
width: 0;
height: 0;
font-size: 0;
visibility: hidden;
}
</style>
</head>
<body>
<a href="javascript:;" class="file">
<input type="file">
</a>
<script>
var file_btn = document.querySelector('.file');
var file_input = file_btn.querySelector('input');
file_btn.addEventListener('click', function(){
file_input.click();
});
</script>
</body>
</html>