我知道这是一篇旧帖子,但这是一种方法。
从这里开始......
https://www.w3schools.com/jsref/prop_fileupload_files.asp
到此结束...
https://jsfiddle.net/trentHarlem/q6zutLjv/11/
仅使用 html css js
HTML
```<div id='input-container'>
<input type="file" id="fileElem" multiple accept="image/*">
<a href="#" id="fileSelect"></a>
<div id="fileList"></div>
</div>
<div id="image-container"></div>
<div id="image-container2"></div>```
CSS
#image-container {
height: 400px;
width: 400px;
background-size: 150%;
}
Javascript
const fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function(e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault();
}, false);
fileElem.addEventListener("change", handleFiles, false);
function handleFiles() {
if (!this.files.length) {} else {
const list = document.createElement("ul");
fileList.appendChild(list);
for (let i = 0; i < this.files.length; i++) {
const li = document.createElement("li");
list.appendChild(li);
const imgContainer = document.getElementById("image-container")
const imgContainer2 = document.getElementById("image-container2")
const img = document.createElement("img");
img.src = URL.createObjectURL(this.files[i]);
// for CSS Background-image
imgContainer.style.backgroundImage = `url("${img.src}")`;
// for HTML src
imgContainer2.innerHTML = `<img width='400px' height='auto'
src='${img.src}'/>`;
// hide input after file selected
fileElem.addEventListener("click", hide());
function hide() {
document.getElementById('input-container').style.display = 'none';
}
}
}
}
这需要一些收紧和本地存储模块,但它适用于 safari 勇敢的 firefox 和 chrome 在这篇文章中