首页 > 解决方案 > 模态图像未出现

问题描述

我正在尝试设置一个单击事件,因此当单击 IMG 时,模态将出现其中的图像。

我试过谷歌搜索和查看这里但无济于事。也许我只是措辞错误。

<div class="modal">
        <div class="modalContent">
          <h2> Full size! </h2>
          <img src="" class="modalImg">
        </div>
      </div>
        <div class="gallery">
              <img src="img/twilight.jpeg" alt="man in the night" class="showcase">
          </div>

          <div class="list">
            <img src="img/code.jpeg" alt="code on a laptop" class="img1">
            <img src="img/desk.jpeg" alt="desk setup" class="img2">
            <img src="img/iphone.jpeg" alt="Iphone x" class="img3">
            <img src="img/keyboard.jpg" alt="glowing keyboard" class="img4">
            <img src="img/lips.jpg" alt="bloody lips" class="img5">
            <img src="img/crowbar.jpg" alt="man holding crowbar" class="img6">
            <img src="img/horror.jpeg" alt="horror image" class="img7">
            <img src="img/hands.jpeg" alt="bloody hands" class="img8">
          </div>
const modal = document.querySelector('.modal');
const img = document.querySelector('.img1');
const myImg = document.querySelector('.modalImg');
img.addEventListener('click', () => {
  modal.style.display = 'block';
  myImg.src = this.src;
});


I'm just attempting to have this work on the first image now, So i'm hoping to make is so on click the image shows in a pop modal. now the modal shows up just fine and has the h2 set but nothing shows up aside from that.

标签: javascript

解决方案


将您的功能从箭头功能更改为正常功能,然后将起作用。

const modal = document.querySelector('.modal');
const img = document.querySelector('.img1');
const myImg = document.querySelector('.modalImg');
-- img.addEventListener('click', () => {
++ img.addEventListener('click', function() {
  modal.style.display = 'block';
  myImg.src = this.src;
});

根据MDN,箭头函数没有自己的 this,它遵循正常的变量查找规则。所以如果需要获取image.src,需要使用function关键字而不是箭头函数。


推荐阅读