You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS实现点击缩略图传src到模态框:模态框图片为空问题排查

问题原因及解决方案

问题根源

你代码里的project_img选中的是.project_img类的div容器,而非容器内部的img标签。div元素本身没有src属性,调用img.getAttribute("src")会返回null,将这个值赋值给模态框图片后,自然显示为null。

两种解决方案

方案一:直接选中缩略图的img标签

修改选择器,直接定位到.project_img下的img元素,点击时直接获取它的src即可:

const modal = document.querySelector(".modal_section");
const modal_img = document.querySelector(".b_p_modal");
// 调整选择器,选中.project_img内部的img
const project_img = document.querySelectorAll(".project_img img");
const close = document.querySelector(".modal_close");

project_img.forEach((img) => {
  img.addEventListener("click", function () {
    modal_img.setAttribute("src", this.getAttribute("src"));
    modal.classList.add("visible");
  });
});

close.addEventListener("click", function () {
  modal.classList.remove("visible");
});

方案二:保留div容器选择,点击时获取内部img的src

如果需要保留点击div容器的交互逻辑,就在点击事件里先找到容器内的img标签,再取它的src:

const modal = document.querySelector(".modal_section");
const modal_img = document.querySelector(".b_p_modal");
const project_img = document.querySelectorAll(".project_img");
const close = document.querySelector(".modal_close");

project_img.forEach((div) => {
  div.addEventListener("click", function () {
    // 获取当前div内部的img元素的src
    const imgSrc = this.querySelector("img").getAttribute("src");
    modal_img.setAttribute("src", imgSrc);
    modal.classList.add("visible");
  });
});

close.addEventListener("click", function () {
  modal.classList.remove("visible");
});

内容的提问来源于stack exchange,提问作者KBoardSurfer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:12:46