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

本文介绍三种美化HTML中inputtype=file上传按钮的方法:利用CSS定位和透明度、label标签的for属性以及onclick事件。推荐使用label标签方法,因其简单且无需额外CSS定位或事件绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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定位,也不需要通过事件绑定。

 

转载于:https://www.cnblogs.com/hao-1234-1234/p/9953887.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值