首页 > 解决方案 > 使用模板文字创建模态框时不会关闭

问题描述

我有一个图片库,每个图片都有模态。图库和模态框是使用模板文字在 javascript 中创建的。模态弹出窗口是使用 iframe 导入的不同 html 文件。

由于某种原因,在外部单击时模态不会关闭。我尝试在 html 中创建 iframe 而不是使用模板文字,在这种情况下我没有任何问题,只是在使用 javascript 制作它们时。

这是正在发生的事情的一个例子。 这个 GitHub 示例

这是两种情况下使用的模态函数:

function modalLinks(tempgal){
    let btnId = "btn" + tempgal.imgn;
    let modId = "id" + tempgal.imgn;
    let getBtnId = document.getElementById(btnId);
    let getModId = document.getElementById(modId);
    getBtnId.onclick = function() {
        console.log('click: btn: ' + this.id + ', modal: ' + getModId.id);
        getModId.classList.toggle('show-popup');
    }
    /* to dispose the popup on click */
    getModId.onclick = function() {
        console.log(this.id +" it's OK");
        this.classList.toggle('show-popup');
    }
}

月亮和它的模态是在 HTML 中创建的。其他两个图像(抱歉,如果它们没有正确显示)是使用模板文字创建的,并且,如您所见(如果您已经看过示例),月亮模式工作正常,但其他两个没有。

如果有人请告诉我发生了什么,那就太好了。

感谢提前。

标签: javascriptiframemodal-dialogtemplate-literals

解决方案


Ok, I just experimented changing things and moving others and got the solution. When making modals with external html's and importing them with iframe, putting the iframe within a div is the best choice.

The iframed modal shoul look like this

<div id="modalid" class="modal-window">
    <iframe class="modal-wrap" src="thelink" frameborder="0"></iframe>
</div>

the css like this

.modal-window{
    display: none;
    position: fixed;
    z-index: 2;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
}
.modal-wrap{
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 50%;
    height: 50%;
}

and the html imported must have this class

.modalcontent{
    position: absolute;
    z-index: 3;
    margin: auto;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%
}

推荐阅读