我如何 link 每个模式 window 到用户点击打开它们的特定图像?

How do I link each modal window to the specific image that the user clicks on to open them?

我在网上寻找解决方案,似乎有一种叫做 data-attribute 的东西可以用来做我想做的事。

我有两个不同的模态 windows,每个都有自己的内容,我想 link 每个到一个特定的按钮(或者在我的例子中,用户将点击)。我尝试输入 "data-attribute",但是当我点击相应的图像时,第二个模式 window(ID 为 fujian 的那个)没有弹出。

对于为什么这不起作用以及我应该怎么做,有没有人有任何建议或想法?

<!--The two image icons that user clicks on-->
<a href='#' onclick='overlay()'><img src="city1.png" alt="sichuan" class="city1"/></a>
<a href='#' onclick='overlay()' data-target="#fujian" data-toggle="modal"><img src="city2.png" alt="sichuan" class="city2"/></a>

<div id="overlay">
   <!--The two separate modal windows-->
   <div class="modal">
       <img src="sichuan.png" alt="sichuan popUp"/>
       <a class="closing" href='#' onclick='overlay()'><img src="/Users/KarenLee/Desktop/exit.png"></img></a>
   </div>
</div>

<div id="overlay">
   <div class="modal" id="fujian">
       <img src="fujian.png" alt="fujian popUp"/>
       <a class="closing" href='#' onclick='overlay()'><img src="/Users/KarenLee/Desktop/exit.png"></img></a>
   </div>
</div>

这是我的 overlay() 功能,如果您需要查看它:

function overlay() {
    el = document.getElementById("overlay");
    el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
  1. id's 在整个文档中必须是唯一的,并且您有重复的 ID <div id="overlay">

  2. 你可以用单一模态实现你想用 2 个模态实现的 data-attributes

  3. 模态 HTML 中缺少关键 div 元素,这就是为什么您的代码只显示模态背景,没有其他任何东西

就您询问的 data-attribute 而言,锚点 <a></a> 元素有两个自定义数据属性:data-toggledata-target。 开关告诉 Bootstrap 要做什么,目标告诉 Bootstrap 哪个元素将要打开。 因此,每当单击 <a></a> link 之类的内容时,都会出现目标为 id 的模态。

假设您有 2 张图片并希望以模态显示,使用默认 bootstrap 行为打开模态,还可以使用 data-attributes 将图像传递给模态,在本例中为 data-image 并使用 bootstrap modal event listener,可以在模态打开时以模态显示图像(不需要 2 个模态)

<a data-target="#fujian" data-toggle="modal" data-image="http://tympanus.net/Tutorials/CaptionHoverEffects/images/1.png" class="btn btn-primary">Image 1</a>
<a data-target="#fujian" data-toggle="modal" data-image="http://tympanus.net/Tutorials/CaptionHoverEffects/images/2.png" class="btn btn-warning">Image 2</a>

模态 HTML 将是

<div id="fujian" class="modal fade">
    <div class="modal-dialog"> //Missing this Div
        <div class="modal-content"> //Missing this Div
            <div class="modal-body">
                <img class="showimage" src="" /> //Image will be shown Here
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

和bootstrap事件侦听器

$(document).ready(function () { //Dom Ready
    $('#fujian').on('show.bs.modal', function (e) { //Event listener
        var image = $(e.relatedTarget).data('image'); //Fetch image url from modal trigger <a> link
        $(".showimage").attr("src", image); //load image in modal
    });
});

Fiddle