Jquery多模式插件

Jquery multiple modals plugin

本文关键字:插件 模式 Jquery      更新时间:2023-09-26

我正在为模式弹出窗口使用这个简单的jquery插件,但它没有用于多个弹出窗口的功能,所以我正在尝试创建自己的插件。

首先,我为打开模态和模态div的按钮添加了唯一索引。HTML是动态创建的。

<button class="my_modal_open" id="1">Open modal</button>
<div id="my_modal" class="1" style="display:none;margin:1em;">
    <a href="#" class="my_modal_close" style="float:right;padding:0 0.4em;">×</a>
    Modal Content
</div>
<button class="my_modal_open" id="2">Open modal</button>
<div id="my_modal" class="2" style="display:none;margin:1em;">
    <a href="#" class="my_modal_close" style="float:right;padding:0 0.4em;">×</a>
    Modal Content
</div>
<button class="my_modal_open" id="3">Open modal</button>
<div id="my_modal" class="3" style="display:none;margin:1em;">
    <a href="#" class="my_modal_close" style="float:right;padding:0 0.4em;">×</a>
    Modal Content
</div>

然后我修改了js,通过适当的索引打开modals。

$(document).ready(function() {
  $('.my_modal_open').click( function() {
        $('#my_modal').css('display','none'); //added
        var open_id = $(this).attr('id'); //added
        $('#my_modal.' + open_id).popup(); //changed to get div id and class               
  });
});

这是有效的,但模态只打开一次。作为修复,我尝试添加

$('#my_modal').css('display','block');

popup()函数工作但模态没有显示在正确的位置之后,第二次。

请分享任何建议。希望有人以前使用过这个插件。

您可能需要查看其他库,如jQuery UI或Twitter Bootstrap,因为它们已经解决了这个问题。如果你想自己滚,我会稍微改变你的做法。

为按钮添加一个属性,用于存储要显示的模式对话框的ID。在下面的例子中,我称之为"数据模态id"。当您单击按钮时,获取该属性的值,并查找具有该ID的模态并显示它:

HTML

<button class="my_modal_open" data-modal-id="1">Open modal</button>
<div id="1" style="display:none;margin:1em;">
    <a href="#" class="my_modal_close" style="float:right;padding:0 0.4em;">×</a>
    Modal Content
</div>
<button class="my_modal_open" data-modal-id="2">Open modal</button>
<div id="2"style="display:none;margin:1em;">
    <a href="#" class="my_modal_close" style="float:right;padding:0 0.4em;">×</a>
    Modal Content
</div>
<button class="my_modal_open" data-modal-id="3">Open modal</button>
<div id="3" style="display:none;margin:1em;">
    <a href="#" class="my_modal_close" style="float:right;padding:0 0.4em;">×</a>
    Modal Content
</div>

jQuery

$(document).ready(function () {
    $('.my_modal_open').click(function () {
        $('#' + $(this).data("modal-id")).popup()
    });
});

工作演示

您可以使用fadeIn()和fadeOut()。

示例

创建类似的东西

<div class="my_modal_background"></div>

其中在css 中

.my_modal_background{ background:#000; position:fixed; width:100%; height:100%; z-indez:0 }
.my_modal_open div{ z-index:1; }

你的Jquery必须像这个

$(document).ready(function () {
    $('.my_modal_open').click(function () {
        $(this).children('div').fadeIn();
        $('.my_modal_background').fadeIn();
    });
});