gpt4 book ai didi

javascript - 如何从数组列表/javascript中弹出图像

转载 作者:行者123 更新时间:2023-12-02 21:18:36 24 4
gpt4 key购买 nike

我有一个页面,显示数组列表中的元素,每个元素都有一个图像,上限为120px。如何在屏幕中间弹出更大尺寸的图像?我已经看到一些可以帮助解决这个问题的插件,但我想在没有任何插件的情况下做到这一点。

html:

<div id="animallist"></div>

JavaScript:

const animals = [{
name: "Cat",
useful: "no",
image: "https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png"
},
{
name: "Dog",
useful: "yes",
image: "https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-1100x628.jpg"
},
{
name: "Fish",
useful: "no",
image: "https://cdn0.wideopenpets.com/wp-content/uploads/2019/10/Fish-Names-770x405.png"
},
]

animals.forEach(addLink);

function addLink(animal, i) {
const div = document.createElement('div');
const animalList = document.createElement('h2');
const image = document.createElement('img');
image.id = "image";
animalList.innerHTML = animal.name + " " +"-"+"useful?" + " "+ animal.useful;
animalList.style.cssText = "text-align:center;"
image.src = animal.image;
div.appendChild(image);
div.appendChild(animalList);
div.dataset.animalName = animal.name;
animallist.appendChild(div);
}

jsfiddle

最佳答案

您必须在开始时使用“display:none”类创建“pop-up”div,然后使用JS删除该“display:none”类并将内部img src更改为您的img。这是工作代码:https://jsfiddle.net/bcdu3L2j/1/

const imgs = document.getElementsByTagName('img');
const imgsArray = Array.from(imgs);

const popUp = document.getElementById('pop-up');
const popImg = document.querySelector('#pop-up img');

function popUpImage(e) {
const imgSrc = e.target.src;
popImg.src = imgSrc;
popUp.classList.remove("hidden");
}

imgsArray.forEach((img) => {
img.addEventListener('click', popUpImage);
})
popUp.addEventListener('click', () => {
popUp.classList.add("hidden");
});

关于javascript - 如何从数组列表/javascript中弹出图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60907852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com