如何改变文件上传的样式?
文件上传默认样式如图,基本是丑的一批,开发中基本上需要改变样式。
要在input标签本身改变样式多少有点麻烦,也不好操作。现在基本上是用别的标签绑定input来实现。下面用button按钮绑定文件上传并改变其样式。
<input type="file" name="file" id="file">
<button id="btn">上传</button>
<span id="sp">文件名字</span>
<script src="assets/lib/jquery.js"></script>
<script>
$(function(){
//为上传按钮绑定点击事件
$('#btn').on('click',function(){
//点击文件上传input
$('#file').click()
})
//为文件上传框绑定事件
$('#file').on('change',function(e){
//console.log(e)
//获取用户选择文件
const filelist=e.target.files
//console.log(filelist)
//文件名放在span显示
$('#sp').html(filelist[0].name)
})
})
</script>
好了,现在基本结构有了,只需要添加稍微加点样式,欧克,搞定了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#file {
display: none;
}
#sp {
display: inline-block;
border: 1px solid #ccc;
width: 200px;
height: 25px;
line-height: 25px;
padding-left: 10px;
}
#btn {
width: 50px;
height: 27px;
line-height: 25px;
background-color: green;
color: #fff;
margin-left: -5px;
}
</style>
</head>
<body>
<input type="file" name="file" id="file" >
<span id="sp">文件名字</span>
<button id="btn">上传</button>
<script src="assets/lib/jquery.js"></script>
<script>
$(function(){
//为上传按钮绑定点击事件
$('#btn').on('click',function(){
//点击文件上传input
$('#file').click()
})
//为文件上传框绑定事件
$('#file').on('change',function(e){
//console.log(e)
//获取用户选择文件
const filelist=e.target.files
//console.log(filelist)
//文件名放在span显示
$('#sp').html(filelist[0].name)
})
})
</script>
</body>
</html>