关于我在网上找到的模态盒插件,我有几个问题。我链接的代码如下:
<li><a href="#" id="country_link"><span id="label">Country: </span><span id="strong">United Kingdom</span></a>
这就是我想用来触发模态框的打开,但我无法弄清楚我是如何将链接指向模态框的,重要的是如果javascript仍然被禁用,它仍将链接到另一个页。我认为防止违约是我需要的,但我不确定。
// Modal Box
// Version 0.1
(function ($) {
$.fn.extend({
leanModal: function (options) {
var defaults = {
top: 100,
overlay: 0.5,
closeButton: null
}
var overlay = $("<div id='lean_overlay'></div>");
$("body").append(overlay);
options = $.extend(defaults, options);
return this.each(function () {
var o = options;
$(this).click(function (e) {
var modal_id = $(this).attr("href");
$("#lean_overlay").click(function () {
close_modal(modal_id);
});
$(o.closeButton).click(function () {
close_modal(modal_id);
});
var modal_height = $(modal_id).outerHeight();
var modal_width = $(modal_id).outerWidth();
$('#lean_overlay').css({
'display': 'block',
opacity: 0
});
$('#lean_overlay').fadeTo(200, o.overlay);
$(modal_id).css({
'display': 'block',
'position': 'fixed',
'opacity': 0,
'z-index': 11000,
'left': 50 + '%',
'margin-left': -(modal_width / 2) + "px",
'top': o.top + "px"
});
$(modal_id).fadeTo(200, 1);
e.preventDefault();
});
});
function close_modal(modal_id) {
$("#lean_overlay").fadeOut(200);
$(modal_id).css({
'display': 'none'
});
}
}
});
})(jQuery);
答案 0 :(得分:1)
我会尽力向你解释它是如何运作的。
你需要两个部分。元素,将触发模态框和模态框元素。
正如您所理解的,这两个部分与href连接。现在棘手的部分是,href中的第一个字符必须是“#”。 modalbox id也必须与href相同,但“#”字符除外。这是代码:
<a href="#my-first-modal-box" id="country_link">
<span id="label">Country: </span><span id="strong">United Kingdom</span>
</a>
<div id="my-first-modal-box"> This is what appears in modal box </div>
现在javascript / jQuery代码。你将在href上简单地调用函数:
$(document).ready(function() {
$("#country_link").leanModal();
});
现在点击链接后,将出现模态框。因为链接以#开头,所以它不会调用新页面或页面重新加载;)(是的,它是棘手的部分)。另外我建议你把这个模态框直接放在你的html代码链接下面。因此,如果关闭javascript,那么模态框只是链接下的简单div,它始终可见。所以你的javascript看起来像这样:
$(document).ready(function() {
$("#my-first-modal-box").hide(); // this will hide modal box with javascript.
// It appears only if you click on link and it
// is visible if javascript is turned off
// you can add some options, like close buttons
var myCloseButton = $("<div class=\"close-button\"></div>");
// you append close button only if it is with javascript
myCloseButton.appendTo("#my-first-modal-box");
$("#country_link").leanModal({ closeButton : myCloseButton });
});