未显示模式图像



我正在尝试设置一个点击事件,所以当点击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.

将函数从箭头函数更改为普通函数即可。

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,则需要使用函数关键字而不是箭头函数。

最新更新