window.URL.createObjectURL
可以用於在瀏覽器上預覽本地圖片或者視頻。以圖片為例,生成url
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> <style> *{ list-style: none; } .img-item { position: relative; vertical-align: middle; width: 100px; height: auto; float: left; } .img-item img{ display: inline-block; width: 100%; } .close { position: absolute; right: 0; top:-5px; width: 20px; height: 20px; } </style> </head> <body> <input type="file" id='check' multiple> <!--multiple屬性可以選擇多張 --> <ul id='imgCon'></ul> </body> </html> <script> var con = document.getElementById('check') var imgList = [] // 顯示的圖片 con.onchange = function () { handleFile(con.files) // console.table(con.files) } function handleFile(files) { if (files.length + imgList.length > 4) { alert('最多4張') // 最多只能選四張,當前選中的和已顯示之和不能大於4 return } if (files[0]) { for (var i = 0; i < files.length; i++) { var img = window.URL.createObjectURL(files[i]) // 將文件生成url imgList.push(img) } show(imgList) } } function show(imgList) { var imgCon = document.getElementById('imgCon') var html = '' for (var i = 0; i < imgList.length; i++) { html += '<li class="img-item"><img src="' + imgList[i] + '" alt=""><span class="close" onclick="delImg(' + i + ')">X</span></li>' } imgCon.innerHTML = html } function delImg(index) { // 刪除顯示的圖片 console.log(con.files) imgList.splice(index, 1) show(imgList) } </script>