input自定义样式上传图片

在我们写网页的时候,有很多各种各样的上传图片的样式,但是input 的 type="file" 的样式是不可被更改的。

其实我们要的只是input的点击,清楚这点就行了。

 

CSS部分

body{
    margin: 0;
}
html,body{
    height: 100%;
}
#box{
    width: 100%;
    height: auto;
}
.img-d{
    margin-top: 30px;
    width: 300px;
    height: 300px;
    text-align: center;
    position: relative;
}
.img-d span{
    display: inline-block;
    width: 100%;
    height: 100%;
    background-image: url("jia.jpg");
    cursor: pointer;
    background-size: 100% 100%;
    background-repeat: no-repeat;
}
#up{
    display: none;
}
.rems{
    display: inline-block;
    width: 25px;
    height: 25px;
    background: red;
    border-radius: 50% 50%;
    font-size: 17px;
    position: absolute;
    top: -6px;
    right: -6px;
    color: white;
    text-align: center;
    line-height: 25px;
    cursor: pointer;
}

 

HTML部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div id="box">
        <div class="img-d">
            <span class="up-s"></span>
            <input type="file" id="up" multiple name="files">
        </div>
    </div>
</body>
</html>
<script src="index.js"></script>

 

JS部分

// span的点击事件
var addBtn = document.querySelector('.up-s');
addBtn.addEventListener('click',function () {
    document.querySelector('#up').value = null;
    document.querySelector('#up').click();
    return false;
},false);

// 处理input点击之后的change事件
document.getElementById("up").addEventListener("change",function(e){
    var files =this.files;
    var reader =new FileReader();
    reader.readAsDataURL(files[0]);
    reader.onload =function(e){
        var dx =(e.total/1024)/1024;
        if(dx>=2){
          alert("文件大小大于2M");
          return;
        }
        var result =this.result;//这里就是转化之后的DataURL
        addBtn.style.backgroundImage = "url("+result+")";
      }
      var rem =document.createElement("i");
      rem.setAttribute("class","rems");
      rem.innerHTML ="x";
      document.querySelector(".img-d").appendChild(rem);
      rem.addEventListener('click',function () {
        this.style.display ="none";
        addBtn.style.backgroundImage = "url(jia.jpg)";
      });
})

 

原理:把<input type="file" id="up" multiple name="files"> 给隐藏掉,然后自己写一个标签,自定义css样式,在js里,点击这个元素然后执行点击input的事件。在操作input的change事件就行了。

 

posted @ 2017-03-19 21:26  _whys  阅读(6333)  评论(3编辑  收藏  举报