仅在 Laravel 中打开模式时加载图像

Load image only when opening the modal in Laravel

描述

我有一张小预览图片,点击它时,会打开一个带有更大图片的模式。

<a onClick="ToggleImage()" class="toggle-img-btn">
<img class="about-img" src="{{asset("storage/images/about_170.jpg")}}" /></a>

@include('inc.imageModal')

图像模态:

<div class="img-modal-background" id="img-modal-background">
  <div class="img-modal-content">
    <input type="checkbox" class="img-close" onClick="ToggleImage()" />
    <a class="img-close-cross"></a>
    <img class="modal-img" src="{{asset("storage/images/about.jpg")}}">
  </div>
</div>

和 opening/closing 模态的 JavaScript 函数:

function ToggleImage() {
    const modalBG = document.getElementById("img-modal-background");
    const modalIMG = document.querySelector(".modal-img");
    if (modalBG.style.display === "flex") {
        modalBG.style.opacity = "0";
        setTimeout(() => {
            modalBG.style.display = "none";
            modalIMG.style.display = "none";
        }, 500);
    } else {
        modalBG.style.display = "flex";
        modalIMG.style.display = "inherit";
        setTimeout(() => {
            modalBG.style.opacity = "1";
        }, 10);
    }
}

问题

我只想在用户打开模式时加载模式中的图像。

我怎样才能做到这一点?

我使用 Laravel 7 和纯 JS。

您可以找到 repo here

感谢您的宝贵时间:)

你可以把你的图像路径放在 js 变量上,并像这样设置属性 img src 依赖于模态状态:

function ToggleImage() {
const modalBG = document.getElementById("img-modal-background");
const modalIMG = document.querySelector(".modal-img");
const img = "storage/images/about.jpg";

if (modalBG.style.display === "flex") {
    modalBG.style.opacity = "0";
    modalIMG.setAttribute("src", "");
    setTimeout(() => {
        modalBG.style.display = "none";
        modalIMG.style.display = "none";
    }, 500);
} else {
    modalBG.style.display = "flex";
    modalIMG.style.display = "inherit";
    modalIMG.setAttribute("src", img);
    setTimeout(() => {
        modalBG.style.opacity = "1";
    }, 10);
}

}