简体   繁体   English

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

[英]How to pop-up an image from array list /javascript

I have got a page that displays my items from an array list, and each of them have an image, that is capped to 120px .我有一个页面显示数组列表中的项目,每个项目都有一个图像,上限为120px What would be the way to pop up that image in the middle of the sreen with bigger size.在屏幕中间弹出更大尺寸的图像的方法是什么。 I have seen some plugins that can help with that, but I wanna do it without any plugins.我已经看到一些插件可以帮助解决这个问题,但我想在没有任何插件的情况下做到这一点。

html: html:

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

javascript: 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提琴手

You have to create 'pop-up' div with 'display: none' class in the beginning, then with JS remove that 'display: none' class and change inner img src to your img.您必须在开始时创建带有 'display: none' 类的'pop-up' div,然后使用 JS 删除该 'display: none' 类并将内部 img src 更改为您的 img。 Here is the working code: https://jsfiddle.net/bcdu3L2j/1/这是工作代码: 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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM