![](/img/trans.png)
[英]how to preload more than one but not all images of a slideshow with jquery
[英]Preload images from more then one file input
我找到了一種在上傳之前預加載圖像的方法,但我有多個文件輸入。 我希望每個輸入文件都預加載圖像。 總的來說不是大問題,但網站上使用的文件輸入數量不穩定。 用戶可以添加上傳圖片塊,以便他可以添加 2 或 3 個,我希望他為每個廣告都可以預加載圖片。 但我的經驗沒有達到它所需要的水平。 所以我的問題是有可能實現嗎? 我為一個特定文件輸入預加載圖像的代碼是這樣的:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.height(50);
};
reader.readAsDataURL(input.files[0]);
}
}
如果用戶添加一個圖像塊,則如下所示:
<div id="divImage-1" class="form-group form-file-upload">
<label id="labelImage-1" for="labelImage2-1">New Picture</label>
<div></div>
<label id="labelImage2-1" for="inputImage-1" class="form-file-upload1">Upload Image</label>
<input id="inputImage-1" type="file" onchange="readURL(this);">
<img id="blah" height="50" alt="Image preview">
</div>
如果用戶創建第二個,則所有 ID ae 計數為 2 (divImage-2)。
讓我們假設你在你的 HTML 中
<button class="btn btn-primary" id="addBtn">Add Image Block</button>
<div class="container"></div>
然后,作為第一步,您需要創建兩個全局變量:
let imageBlockCout = 0
計算圖像塊的數量。let addedPicSet = nnew Set()
一組其他塊正在使用的圖片名稱。然后每次點擊添加按鈕,我們都會添加一個新的圖像塊,代碼如下:
$(
$.parseHTML(
`<div class="row">
<input type="file" multiple id="photos-${imageBlockCount}">
<div id="gallery-${imageBlockCount}" class="row"></div>
</div>`
)
).appendTo(".container");
現在,對於添加的每個文件輸入,您需要附加一個 on-change 偵聽器:
let currentBlockCount = imageBlockCount;
$("#photos-" + imageBlockCount).on("change", function () {
let input = this;
if (!input.files) {
return;
}
//for every image that has been read by FileReader we show it
//in its own card inside its button gallery
let onFileLoaded = function (event) {
$(
$.parseHTML(
`<div class="col-sm-3">
<div class="card">
<img
class="card-img-top"
src="${event.target.result}">
</div>
</div`
)
).appendTo("#gallery-" + currentBlockCount);
};
//input.files is an array like object, so we convert it to array
Array.from(input.files)
.filter(
//first we filter images which are already in use
(file) => !addedPicSet.has(file.name)
)
.forEach((file) => {
let reader = new FileReader();
//we attach an onLoad listener for each reader
reader.onload = onFileLoaded;
//then we tell the reader object which file to read
reader.readAsDataURL(file);
//add the image name in the set of used image names
addedPicSet.add(file.name);
});
});
我也做了一支筆來幫助你: https : //codepen.io/abdullah-shabaz/pen/qBdvZMQ
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.