上传文件的样式

在网上找了很久上传文件的样式,并没有适合自己的,现在推荐一个样式给大家,可以看到自己是否选到文件和文件名。效果如下图所示:

 

html 代码如下:

<div class="uploading">
    <span>上传文件:</span>
    <input class='view' id="viewfile" type="text" onmouseout="document.getElementById('uploadfile').style.display = 'none';" readonly />
    <label class="filelab" for="uploadfile" onmouseover="document.getElementById('uploadfile').style.display = 'block';">浏览</label> 
    <input class="upload" id="uploadfile" name="uploadfile" type="file" />
</div>

 

css 代码如下:

.uploading {
    position: relative;
    height: 28px;
}
.uploading span {
    float: left;
    line-height: 28px;
}
.uploading .view {
    float: left;
    width: 120px;
    height: 26px;
    padding: 0 0 0 10px;
    line-height: 26px;
    border: 1px solid #d2d2d2;
}
.uploading .filelab {
    display: inline-block;
    float: left;
    width: 68px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    color: #fff;
    background: #bd3a39;
}
.uploading .upload {
    position: absolute;
    left: 302px;
    width: 68px;
    height: 28px;
    opacity: 0;
    filter: alpha(opacity=0);
}

 

最后 js代码如下:

var uploadfile = document.getElementById('uploadfile');
var viewfile   = document.getElementById('viewfile');
uploadfile.onchange = function() {
    var path = uploadfile.value.split('\\'); 
    viewfile.setAttribute('value', path[path.length - 1]);
    uploadfile.style.display = 'none';
}

 

对于第4行代码,可能有点难理解,如果打印出 uploadfile.value 值,它是 'C:\fakepath\demo.rar', 'C:\fakepath\' 是自动生成的假路径,只要把假路径删除就行了,通过 split 方法把这个字符串以 '\' 分隔生成一个数组 ["C:", "fakepath", "demo.rar"],取出数组中下标为2的就是想要的文件名 'demo.rar',如果重新选择文件时取消上传,也会触发 change 事件,uploadfile.value 值为空,同时也会把之前选的文件删除。

 

posted @ 2016-08-09 11:40  yu.l  阅读(590)  评论(0编辑  收藏  举报