在模态窗口中显示HTML标记

我有一个JavaScript函数,它接收一个参数,其值是HTML的一个片段。 我想在居中的modal dialog中显示此内容(使用关闭按钮)。

var showContent = function(content) { // TODO show content in model dialog } 

我已经在使用JQuery,并且不介意在必要时安装另一个插件,只要它相当小。 我没有使用JQueryUI而宁愿避免使用它,因为我不会将它用于其他任何东西。

这个插件看起来很有希望: SimpleModal (缩小9.6KB)

您可以使用所选元素的内容打开它,或使用某些HTML作为内容:

 $("selector").modal(); $.modal("

Hello world

");

所以在你的情况下,你可以这样做:

 var showContent = function(content) { $.modal(content); } 

您只需要2种款式:

 #simplemodal-overlay { ... } #simplemodal-container { ... } 

它看起来像这样(在演示页面上):

SimpleModal示例

你可以在没有任何插件的情况下完成它…只需使用它。

HTML:

 

CSS:

  .overlay-div { display:none; z-index:100; background-color:rgba(0,0,0,0.44); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#44000000,endColorstr=#44000000)\9; //for IE position:absolute; top:0; left:0; } .overlay-div .modal-div { width:500px; height:480px; position:fixed; top:50%; left:50%; margin:-240px 0 0 -250px; //must be proportional to width and height padding:25px; background:#fff; z-index:1; } .x-button { cursor:pointer; } 

使用Javascript:

 var showContent = function(content) { $(".overlay-div").width($("html").width()); $(".overlay-div").height(getDocHeight()); $(".modal-div").append(content); $(".overlay-div").show(); } $("#x-button").click(function () { $(".overlay-div").hide(); }); //Cross-browser way to get page height function getDocHeight() { var D = document; return Math.max( Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight) ); }