商业合作
免费在我们的网站上发布一篇文章
公众号承接推广任务
联系我们 微信号码: 18003606519
默认的文件上传按钮相当难看,烦人的是没有办法直接通过css设置样式。Nwx天宁日记|网页模板_网页设计_网站建设
我们可以将 CSS 不透明度和位置属性与 jQuery change() 方法结合使用,只需要定义大小、宽度和颜色等,效果非常好,按钮样式依赖相对层的DIV。Nwx天宁日记|网页模板_网页设计_网站建设
注意:表单不显示文件名,需要在文件选择后触发事件,以javascript方式调用函数来获取数据。Nwx天宁日记|网页模板_网页设计_网站建设
 
美化上传表单按钮演示图

HTML

<!DOCTYPE html>
<html>
<head>
    <title>CSS美化上传表单和按钮 | 天宁日记</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>  
  <form class="form">
    <div class="file-upload-wrapper" data-text="未选择任何文件!">
      <input name="file-upload-field" type="file" class="file-upload-field" value="">
    </div>
  </form>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="main.js"></script>
</body>
</html>

CSS

@import url(https://fonts.googleapis.com/css?family=Lato:400,700,300);
body {
  margin:0;
  padding:0;
  font-family: "Lato", sans-serif; 
  background: -webkit-linear-gradient(to right, #514A9D, #24C6DC); 
  background: linear-gradient(to right, #514A9D, #24C6DC);  
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}  
.form{
  width:400px;
}
.file-upload-wrapper{
  position:relative;
  width:100%;
  height:60px;
  cursor: pointer;
}
.file-upload-wrapper::after{
  content:attr(data-text);
  font-size: 18px;
  position:absolute;
  top:0;
  left:0;
  background:#fff;
  padding:10px 15px;
  display: block;
  width:calc(100% - 40px);
  pointer-events:none;
  z-index: 20;
  height:40px;
  line-height: 40px;
  color:#999;
  border-radius: 5px 10px 10px 5px;
  font-weight: 300;
}
.file-upload-wrapper::before{
  content:"选择上传";
  position:absolute;
  top:0;
  right:0;
  display: inline-block;
  height:60px;
  background: -webkit-linear-gradient(to right, #24C6DC, #514A9D);
  background: linear-gradient(to right, #24C6DC, #514A9D);
  color:#fff;
  font-weight: 600;
  z-index: 25;
  font-size: 16px;
  line-height: 60px;
  padding:0 15px;
  text-transform: uppercase;
  pointer-events: none;
  border-radius: 0 5px 5px 0;
  transition: 0.5s ease-in-out;
}
.file-upload-wrapper:hover::before{
  background: -webkit-linear-gradient(to right, #514A9D, #24C6DC);
  background: linear-gradient(to right, #514A9D, #24C6DC);
}
.file-upload-wrapper input{
  opacity: 0;
  position:absolute;
  top:0;
  right:0;
  bottom:0;
  left:0;
  z-index: 99;
  height:40px;
  margin:0;
  padding:0;
  display:block;
  cursor: pointer;
  width:100%;
}

JS

 $("form").on("change", ".file-upload-field", function(){
     $(this).parent(".file-upload-wrapper").attr("data-text",$(this).val().replace(/.*(\/|\\)/,''));
 })
帝国cms使用自定义页面生成Sitemap
CSS 打造19种 hr 的样式与颜色