input file类型自定义样式-按钮

我们在做页面时有时候为了让上传这种类型的输入看起来更加美观,但是由于其自身往往是无法定义样式的,所以我们经常用按钮来 “替代” 它,接下来讲讲其原理和实践过程。原理:为了让input[type='file']看起来更像一个button,我们首先先采用绝对定位定义一个<a>标签,然后采用绝对定位在相同的位置定义一个和<a>大小完全相同的<input type='file'>,并把其透明度设置为0,最后再定义一个div显示上传的文件名即可。为了方便吧css直接写在html里,简要代码如下:

<!doctype html>
<html>
    <head>
        <style>
            *
            {
                margin: 0;
                padding: 0;
            }
            /*蓝色按钮,绝对定位*/
            .blueButton
            {
                position: absolute;
                display: block;
                width: 100px;
                height: 40px;
                background-color: #00b3ee;
                color: #fff;
                text-decoration: none;
                text-align: center;
                font:normal normal normal 16px/40px 'Microsoft YaHei';
                cursor: pointer;
                border-radius: 4px;
            }
            .blueButton:hover
            {
                text-decoration: none;
            }
            /*自定义上传,位置大小都和a完全一样,而且完全透明*/
            .myFileUpload
            {
                position: absolute;
                display: block;
                width: 100px;
                height: 40px;
                opacity: 0;
            }
            /*显示上传文件夹名的Div*/
            .show
            {
                position: absolute;
                top:40px;
                width: 100%;
                height: 30px;
                font:normal normal normal 14px/30px 'Microsoft YaHei';
            }
        </style>
        <script src="../jquery-3.1.0.min.js"></script>
        <title>file自定义上传</title>
    </head>
    <body>
        <a href='javascript:void(0);' class="blueButton">选择文件</a>
        <input type="file" class="myFileUpload" />
        <div class="show"></div>
    </body>
</html>
<script>
    $(document).ready(function()
    {
        $(".myFileUpload").change(function()
        {
            var arrs=$(this).val().split('\\');
            var filename=arrs[arrs.length-1];
            $(".show").html(filename);
        });
    });
</script>

点击后页面如下:


  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值