javascript - 模态图像未出现
问题描述
我正在尝试设置一个单击事件,因此当单击 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,需要使用function关键字而不是箭头函数。
推荐阅读
- asp.net - 表单不会在 POST 请求中绑定到模型
- sql-server - 其他 3 个不同表格的表格评论
- python - 计算体重指数
- java - TreeSet 不添加最后一个元素
- bash - 来自 printf 的 Docker ENV 值不起作用
- sql - 编写 SQL 查询以排除日期早于具有特定标志的记录的记录
- reactjs - 浏览器导航不适用于使用 BrowserRouter 的反应路由器 v5
- python - 用前面提到的人替换人称代词(嘈杂的 coref)
- javascript - Cloudflare worker 在 Javascript 中实现路由监听器
- c - 用于无向(未加权)图的 C 中的邻接表