input type=file 上传文件样式美化(转载)

时间:2023-03-09 18:50:47
input type=file 上传文件样式美化(转载)

input type=file 上传文件样式美化

来源:https://www.jianshu.com/p/6390595e5a36

在做input文本上传时,由于html原生的上传按钮比较丑,需要对其进行美化,radio和checkbox类似

主要想到以下几种方法,欢迎大家补充

1. 通过position和opacity实现

  • input设置:透明度为0,position为绝对定位,font-size足够大
  • input外面套一层a或div等标签(此处以a举例),a设置:position为相对定位,overflow: hidden(为了避免在非a区域点击打开选择文件)

代码如下:

<html>

<head>
<style>
.ui-upload {
font-size: 14px;
width: 80px;
height: 30px;
line-height: 30px;
text-align: center;
position: relative;
cursor: pointer;
color: #fff;
background: #00abff;
border-radius: 3px;
overflow: hidden;
display: inline-block;
text-decoration: none;
} .ui-upload input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
filter: alpha(opacity=0);
cursor: pointer
}
</style>
</head> <body>
<a href="javascript:;" class="ui-upload">
<input type="file" />upload
</a>
</body> </html>

2. 通过label标签的for属性实现

for 属性规定了label与哪个表单元素进行绑定,包含显式联系和隐式联系两种

  • 显式联系:

以显式形式和控件联系起来,for属性的值和控件的id要保持一致

<label for="upload">upload</label>
<input type="file" id="upload" />
  • 隐式联系:

在 <label> 标签中放入控件隐式地连接起来

<label>uplaod<input type="file" /></label>

代码如下:

<html>

<head>
<style>
.ui-upload {
height: 30px;
width: 80px;
background-color: #00abff;
font-size: 14px;
line-height: 30px;
cursor: pointer;
display: inline-block;
text-align: center;
color: #fff;
border-radius: 3px;
margin-left: 20px;
}
</style>
</head> <body>
<label for="upload" class="ui-upload">upload</label>
<input type="file" id="upload" style="display: none;" />
<label class="ui-upload">upload<input type="file" style="display: none;" /></label>
</body> </html>

3. 通过onclick事件获取input操作
代码如下:

<html>

<head>
<style>
.ui-upload {
height: 30px;
width: 80px;
background-color: #00abff;
font-size: 14px;
line-height: 30px;
cursor: pointer;
display: inline-block;
text-align: center;
color: #fff;
border-radius: 3px;
border: 0px;
margin-left: 20px;
}
</style>
</head> <body>
<button class="ui-upload" onclick="document.getElementById('upload').click()">upload</button>
<input type="file" id="upload" style="display:none;" />
</body> </html>

结论

本文推荐大家使用第二种label标签实现,因为它不需要繁琐css定位,也不需要通过事件绑定。

input type=file 上传文件样式美化(转载)