Show modal dialog with 'x' without using jqueryui

…衆ロ難τιáo~ 提交于 2019-11-29 17:29:54

I think you're looking for something like this:

$('.modal .titlebar a').click(function() {
  $(this).parents('.modal').hide();
});

$('button.open-modal').click(function() {
  $('#something').show();
});

Here's a very basic version:

$("<iframe id='shim' src='http://jsbin.com/abira4'>").css({
    width: "100%",
    height: "100%",
    position: "absolute",
    left: "0px",
    top: "0px",
    zIndex: "100",
    backgroundColor: "#fff",
    opacity: "0.5"
}).appendTo(document.body);
$("<div>Hi there, click me to dismiss</div>").css({
    zIndex: "101",
    border: "1px solid black",
    backgroundColor: "#ecc",
    position: "absolute",
    left: "100px",
    top: "100px"
}).appendTo(document.body)
  .click(function() {
    $(this).remove();
    $("#shim").remove();
});

Live example

How it works:

  • We create an iframe to act as a shim over the body of the page. This eats any clicks outside the "dialog box" div we add a moment later, and also deals with the issue of OS-rendered controls and flash animations popping to the top. We also make it semi-transparent (in this case, background-color is #f0f0f0 and opacity is 50%) so it "greys out" the underlying document. This is absolutely positioned at 0,0 with 100% width and height, and a z-index of 100 (this has to be higher than anything else on the page). The src of the iframe should be a blank document.
  • We then create a div for the "dialog box" which is also absolutely positioned and has a z-index higher than the iframe shim.

Now, there are a lot of variations. For instance, there's no reason at all you can't have the model div markup in the HTML document rather than in the script — -- just give it display: none until you need it. Things like that.

Obviously, this version lets you click anywhere on the dialog box to dismiss it, but it's easily modified to only allow closing with an [X] somewhere. And to say that it could use some styling would be to...put it mildly.

All that said, I can't claim it's remotely bulletproof. That's why well-tested plug-ins are for. :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!