美文网首页
input file样式包装

input file样式包装

作者: 詹小云 | 来源:发表于2017-05-26 10:55 被阅读0次

    初次使用html5的新标签inputp[type="file"]那时,看见标签样式的那一刻我是沉默的,怎么可以这么丑?所以我就动动小手,准备美化一下。于是写下了以下代码:

    <!--html-->
    <input type="file" id="style"/>
    
    /*css*/
    #style{
        width: 168px;
        height: 38px;
        background: #fff;
        border: 1px #CFCFCF solid;
        border-radius: 5px;
    }
    

    摇头晃脑轻松自在地打开chrome,脑袋里已经自动播放样式了,然而看到的样式还是...辣么丑。

    丑丑的input

    于是我就发挥我的聪明才智Google了一下,发现大多人的做法都是相差无几的,做法如下:
    1.在input外边包装一层a标签 ,并设置绝对定位

    1. input的透明度设置为0
    2. 把要出现的2文字写在input旁边并设置相对定位
    3. 把样式写给a标签,但是不能设置宽高,不然点击就会直接点a标签,而input就被覆盖了。
      嘻嘻,写个小demo:
    <!--html-->
    <a href="javascript:(void)" class="upload-wrap">
        <input id="upload" type="file"/>
        <span class="upload-icon">上传文件</span>
    </a>
    
    /*css*/
    #upload {
        opacity: 0;
        width: 138px;
        height: 38px;
    }
    .upload-wrap {
        position: relative;
        display: inline-block;
    }
    .upload-icon {
        position: absolute;
        top: 7px;
        left: 24px;
        color: black;
    }
    
    最终样式

    好的,然后我们会发现,选择文件后的路径也被opacity为0了,这是后就要用到我们强大的js了。哈哈哈哈哈好吧,其实也只有几行代码。如下:

    var upload = document.getElementById('upload');
    upload.onchange = function(){
          console.log(this.value);
    }
    

    相关文章

      网友评论

          本文标题:input file样式包装

          本文链接:https://www.haomeiwen.com/subject/cygaxxtx.html