前端如何更改文件上传的样式?

如何改变文件上传的样式?

文件上传默认样式如图,基本是丑的一批,开发中基本上需要改变样式。

在这里插入图片描述

要在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>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值