我有一個通過 .prepend() 方法顯示影像的界面,我試圖通過單擊關閉按鈕來逐個洗掉影像,并通過單擊按鈕來洗掉所有影像,但我不知道如何做 ?
這是下面的影像串列界面,截至目前顯示 3 張影像我如何附加關閉按鈕并單獨洗掉影像以及單擊 1 次。

HTML:
<div id="imageList">
</div>
JS:
//Images are stored in this array as base64
var imagesBase64 = [];
// add images in the array ImagesBase64
function addToDownload() {
imagesBase64.push(dataURL);
appendImageToList(dataURL);
}
const imageList = document.getElementById("imageList");
function appendImageToList(image) {
var img = document.createElement("img");
img.src = image;
imageList.prepend(img);
}
uj5u.com熱心網友回復:
我制作了一個演示,它或多或少地按照您的要求(但使用 jQuery)。該頁面使用硬編碼在陣列中的圖片串列進行初始化。每張圖片都被附加到自己容器內的#imageList 中,當您要從串列中洗掉圖片時,會添加一個小紅框來捕獲單擊事件。最重要的是,有一個按鈕可以一次洗掉所有這些:
//a list of img urls needed to feed the list of pictures with some
const images = ['https://www.w3schools.com/css/img_5terre.jpg', 'https://www.w3schools.com/css/img_forest.jpg', 'https://www.w3schools.com/css/img_lights.jpg', 'https://www.w3schools.com/css/img_mountains.jpg'];
//inits the imageList with pictures coming from images constant
//..so when the document is ready,
$(document).ready(() => {
//for each url picture in the images constant
images.forEach((o, i) => {
//append a picture to imageList having that url
appendImageToList(o);
});
});
//appends an image to the list (where image is a picture url)
function appendImageToList(image) {
var img = document.createElement("img");
img.src = image;
//the img will be enclosed in a container
let container = $('<div>', {
class: 'imgContainer'
});
container.append(img);
//creates the close handle for this new picture and adds an event handler on its click event
let closeHandle = $('<div>', {
class: 'closeHandle'
});
//adds content x to the close handle
closeHandle.append('<i ></i>');
closeHandle.click(() => {
//when the button is clicked, remove this image from the list
removeOneImageFromList($(event.target).closest('.imgContainer'));
});
container.append(closeHandle);
//adds the container inside the imageList
$('#imageList').prepend(container);
}
//removes all images from the list
function removeAllImages() {
$('#imageList .imgContainer').remove();
}
//removes a specific image from the list
function removeOneImageFromList(imgParentElement) {
$(imgParentElement).remove();
}
/* rule to style every single img container */
#imageList .imgContainer {
position: relative;
width: fit-content;
}
/* rule to style the close handle */
#imageList .closeHandle {
position: absolute;
top: 15px;
right: 15px;
text-align: center;
cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.0.slim.js"></script>
<button type="button" onclick="removeAllImages();">Remove all images</button>
<br><br>
<div id="imageList">
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457364.html
標籤:javascript jQuery
