在咱們寫網頁的時候,有不少各類各樣的上傳圖片的樣式,可是input 的 type="file" 的樣式是不可被更改的。css
其實咱們要的只是input的點擊,清楚這點就好了。html
CSS部分app
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部分this
<!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部分url
// 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事件就好了。spa