没有jQuery的模态对话框

20

我需要使用JavaScript在网页上创建模态对话框。通常这很容易,因为我可以使用像jQueryUI或BlockUI这样的东西,但是这里有一个限制,即我不被允许使用jQuery,并且我需要支持IE9 Quirks模式(即没有HTML5 doctype)。我找不到任何关于我所需要的内容的在线资料。有人有什么建议吗?谢谢。


有一个名为 ModaliseJS 的东西,它运行速度飞快,无需依赖,只做它应该做的事情。 - Alexis Paques
https://github.com/tomloprod/tomloprodModal - tomloprod
7个回答

34

如何用一个居中的div实现叠加效果呢?

你可以创建一个div并隐藏它(使用javascript):

 <div id="overlay">
  <div>
      <p>Content you want the user to see goes here.</p>
  </div>
 </div>

覆盖层的CSS样式可以如下所示:

 #overlay {
    visibility: hidden;
    position: absolute;
    left: 0px;
    top: 0px;
    width:100%;
    height:100%;
    text-align:center;
    z-index: 1000;
 }

然后您可以使用JavaScript来切换遮罩层

中内容的可见性:

 function overlay() {
    el = document.getElementById("overlay");
   el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
 }

更多示例请参见:http://raventools.com/blog/create-a-modal-dialog-using-css-and-javascript/


这个解决方案有两个问题。首先,您必须选择一个背景颜色。否则,您将得到透明颜色的混乱。我不知道如何解决第二个问题。这是您提出的解决方案的示例。向下滚动,在窗口下面。您会发现您的“窗口”跨度不超过屏幕高度。即使将背景设置为浅灰色,混乱也会出现在下面。背景没有覆盖整个重叠页面。也许我们应该替换body。顺便说一下,这被称为“玻璃窗格”方法。 - Val
1
应该是 position: fixed; 吧?将覆盖层附加到窗口而不是文档。- http://jsbin.com/kepahehino/edit?output - MikeB

6
我创建了一个名为tomloprodModal的库,它可以满足你的需求。这是一个简单且可配置的javascript库,用于创建无依赖的响应式和极简风格的模态窗口。
希望能对你有所帮助。

安装:

只需下载并添加 tomloprodModel.csstomloprodModel.js 到您的网站即可。

您也可以使用bower: bower install tomloprodModal 或使用npm: npm install tomloprodModal


初始化:

Javascript:

TomloprodModal.start({
    closeOut: true,
    bgColor: "#FFFFFF",
    textColor: "#333333"
});

模态弹窗示例:

<div class="tm-modal tm-effect tm-draggable" id="logInPopUp">
    <div class="tm-wrapper">
        <div class="tm-title">
            <span class="tm-XButton tm-closeButton"></span>  
            <h3 class="tm-title-text">Lorem Ipsum...</h3> 
        </div>
        <div class="tm-content" >
            <div style="text-align:center">
                <img width="250" src="http://s3.favim.com/orig/47/animal-cat-cute-kitty-surprise-Favim.com-434324.jpg"/>
            </div>
            <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt.
            </p>
        </div>
    </div>
</div>

结果:

在此输入图片描述


或者,您可以创建没有任何HTML的模态窗口:

TomloprodModal.create({
    bgColor: "#FFFFFF",
    textColor: "#333333",
    title: "Hi!",
    content: "Nothing to say",
    closeTimer: 1000
});

Documentation:

https://github.com/tomloprod/tomloprodModal


Demo:

http://codepen.io/tomloprod/pen/kkYxWY


这很棒,但是当我使用它时,我会得到这个错误:TypeError: Cannot read property 'addEventListener' of null @ Object.openModal;不过它仍然可以工作。 - Russell Chisholm
我有一大堆HTML...发生的情况是没有.tm-overlay元素。我没有添加;也许是我在文档中错过了什么。 - Russell Chisholm

0

我已经编写了一些简单的JavaScript函数,专门用于这个目的,并提供了一个演示页面来展示如何使用它们。您可以在http://www.interbit.com/demos/modal.html上查看。

我编写的函数名为MsgBox()、YesNo()和YesNoCancel(),它们执行其名称所示的操作。

要使用它们,只需复制上面链接中的JavaScript文件,并将其包含在您的HTML中。请不要仅仅链接到该文件。相反,请复制它,因为我可能随时更改或删除它。

样例:

MsgBox("This is a message for the user.", "This is the title");
MsgBox("This is a message for the user.", "This is the title", "JSSnippetToCall();");
YesNo("Are you sure you want to do this?", "Please Confirm", "JSSnippetToCallOnYes();", "JSSnippetToCallOnNo();");
YesNoCancel("Are you sure you want to do this?", "Please Confirm", "JSSnippetToCallOnYes();", "JSSnippetToCallOnNo();", "JSSnippetToCallOnCancel();");

我还包括了一个名为JavaScriptError()的函数,它接受一个JavaScript错误对象并将其格式化以供用户显示,适用于在try/catch块中使用:
try {
    <your JavaScript code here>
} catch (e) {
    JavaScriptError(e);
}

这是代码的完整清单,正如其中一位评论者建议的那样。您可以在所有项目中使用它。我对于想让你给我信用的嘲讽性评论有些意见,但实际上我只是要求常识礼貌。除非您窃取代码并声称自己编写了它,否则我不打算起诉任何人。

/**************************************************************************************************/
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/**************************************************************************************************/
/* The functions below are each self-contained and can be copied into any HTML file by themselves
/* and used.  The CSS styling is accomplished by using the STYLE attribute on each HTML tag.  There
/* is no need to use external CSS.  Of course, once you copy the code you can modify it to suit
/* your needs, including changing the styling.  But be careful, especially with the msgBoxDivStyle,
/* because some of it is necessary to achieve the desired effect.
/*
/* You are free to simply copy this JavaScript code into your application, as long as you include
/* the copyright notice in each copy of the code you make.  No exceptions.  If you don't, and I
/* find out, I'll sue you for enough money to retire on.  Because that's just rude and rude 
/* people need to be sued to make the world a better place.  You are also free to modify the code
/* to suit your needs.  But if you do, you still need to give me credit.
/*
/* To see how these functions can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/*
/* I recognize that this code could easily have been written more efficiently, and without some of
/* the redundancy.  I intentionally wrote it the way I did to make it more easily understandable
/* and modifiable to meet your needs.
/**************************************************************************************************/

/**************************************************************************************************/
/* Function MsgBox
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: Message, WindowTitle, onOK
/* Description: This function displays a modal message box with a single OK button.
/*              When the user clicks the OK button the box is removed and the JavaScript provided
/*              in the onOK parameter, if any, is called.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function MsgBox(msg, title, onOK) {

    try {
        var msgBoxDivStyle = "background: rgba(127, 127, 127, 0.6);height: 100%;position: absolute;width: 100%;z-index: 9999;";
        var msgBoxTitleStyle = "background-color: #00478A;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxErrorTitleStyle = "background-color: red;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxSuccessTitleStyle = "background-color: green;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxWarningTitleStyle = "background-color: orange;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxContentsStyle = "background: rgba(255, 255, 255, 1);background-color: white;border: 1px solid black;box-shadow: 6px 6px 6px #070707;";
        msgBoxContentsStyle += "left: 30%;position: absolute;resize: vertical;text-align: center;top: 15%;width: 40%;";
        var msgBoxTextStyle = "font-size: 18px;overflow: auto;padding: 20px;text-align: center;";
        var msgBoxButtonStyle = "margin: 20px;";

        var msgDiv = "";

        if (title == null) {
            title = "Information";
        }

        if (onOK == null) {
            onOK = "";
        }

        titleStyle = msgBoxTitleStyle;
        if (title == "Error" || title == "JavaScript Error" || title == "Exception") {
            titleStyle = msgBoxErrorTitleStyle;

        } else if (title == "Success") {
            titleStyle = msgBoxSuccessTitleStyle;

        } else if (title == "Warning") {
            titleStyle = msgBoxWarningTitleStyle;
        }

        msgDiv += "<div id='msgboxDiv' style='" + msgBoxDivStyle + "'>";  // Covers the entire body to prevent any interaction with controls in the body.
        msgDiv += "<div id='msgboxContents' style='" + msgBoxContentsStyle + "'>";  // Contains the messagebox itself
        msgDiv += "<div id='msgboxTitle' style='" + titleStyle + "'>" + title + "</div>";
        msgDiv += "<div id='msgboxText' style='" + msgBoxTextStyle + "'>" + msg + "</div>";  // Contains the text of the message to be displayed.
        msgDiv += "<button id='answerOK' tabindex='1' style='" + msgBoxButtonStyle + "' accesskey='K' onclick='" + onOK + "document.body.removeChild(this.parentElement.parentElement);'>O<u>K</u></button>";
        msgDiv += "</div></div>";  // Closes the modalBox and modalDiv tags

        document.body.insertAdjacentHTML("afterBegin", msgDiv);

        // This next line is necessary so that the new elements can be referred to in the following JavaScript code.
        document.body.focus();

        // Disable the tab key so that the user can't use it to get to the other controls on the page.
        document.getElementById('answerOK').onkeydown = function(e){if(e.keyCode==9){return false;}}
        document.getElementById('answerOK').focus();

    } catch (e) {
        JavaScriptError(e);
    }
}


/**************************************************************************************************/
/* Function YesNo
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: Message, WindowTitle, onYes, onNo
/* Description: This function displays a modal message box with two buttons labeled "Yes" and "No".
/*              When the user clicks either button the box is removed and the appropriate
/*              JavaScript (passed in the onYes and onNo parameters) is executed.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function YesNo(msg, title, onYes, onNo) {

    try {
        var msgBoxDivStyle = "background: rgba(127, 127, 127, 0.6);height: 100%;position: absolute;width: 100%;z-index: 9999;";
        var msgBoxTitleStyle = "background-color: #00478A;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxErrorTitleStyle = "background-color: red;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxSuccessTitleStyle = "background-color: green;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxWarningTitleStyle = "background-color: orange;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxContentsStyle = "background: rgba(255, 255, 255, 1);background-color: white;border: 1px solid black;box-shadow: 6px 6px 6px #070707;";
        msgBoxContentsStyle += "left: 30%;position: absolute;resize: vertical;text-align: center;top: 15%;width: 40%;";
        var msgBoxTextStyle = "font-size: 18px;overflow: auto;padding: 20px;text-align: center;";
        var msgBoxButtonStyle = "margin: 20px;";

        var msgDiv = "";

        if (title == null) {
            title = "Confirm";
        }

        if (onYes == null) {
            onYes = "";
        }

        if (onNo == null) {
            onNo = "";
        }

        msgDiv += "<div id='msgboxDiv' style='" + msgBoxDivStyle + "'>";  // Covers the entire body to prevent any interaction with controls in the body.
        msgDiv += "<div id='msgboxContents' style='" + msgBoxContentsStyle + "'>";  // Contains the messagebox itself
        msgDiv += "<div id='msgboxTitle' style='" + msgBoxTitleStyle + "'>" + title + "</div>";
        msgDiv += "<div id='msgboxText' style='" + msgBoxTextStyle + "'>" + msg + "</div>";  // Contains the text of the message to be displayed.
        msgDiv += "<button id='answerYes' tabindex='1' style='" + msgBoxButtonStyle + "' accesskey='Y' onclick='" + onYes + "document.body.removeChild(this.parentElement.parentElement);'><u>Y</u>es</button>";
        msgDiv += "<button id='answerNo' tabindex='2' style='" + msgBoxButtonStyle + "' accesskey='N' onclick='" + onNo + "document.body.removeChild(this.parentElement.parentElement);'><u>N</u>o</button>";
        msgDiv += "</div></div>";  // Closes the modalBox and modalDiv tags

        document.body.insertAdjacentHTML("afterbegin", msgDiv);

        // This next line is necessary so that the new elements can be referred to in the following JavaScript code.
        document.body.focus();

        // Intercept the tab key so that the user can't use it to get to the other controls on the page.
        document.getElementById('answerYes').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerNo').focus();return false;}}
        document.getElementById('answerNo').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerYes').focus();return false;}}

        // Put the user's focus on the Yes button.
        document.getElementById('answerYes').focus();

    } catch (e) {
        JavaScriptError(e);
    }
}


/**************************************************************************************************/
/* Function YesNoCancel
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: Message, WindowTitle, Callback
/* Description: This function displays a modal message box with three buttons labeled "Yes", "No",
/*              and "Cancel".  When the user clicks any of the buttons the box is removed and the
/*              appropriate JavaScript (passed in the onYes, onNo, and onCancel parameters)
/*              is called, if any.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function YesNoCancel(msg, title, onYes, onNo, onCancel) {

    try {
        var msgBoxDivStyle = "background: rgba(127, 127, 127, 0.6);height: 100%;position: absolute;width: 100%;z-index: 9999;";
        var msgBoxTitleStyle = "background-color: #00478A;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxErrorTitleStyle = "background-color: red;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxSuccessTitleStyle = "background-color: green;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxWarningTitleStyle = "background-color: orange;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxContentsStyle = "background: rgba(255, 255, 255, 1);background-color: white;border: 1px solid black;box-shadow: 6px 6px 6px #070707;";
        msgBoxContentsStyle += "left: 30%;position: absolute;resize: vertical;text-align: center;top: 15%;width: 40%;";
        var msgBoxTextStyle = "font-size: 18px;overflow: auto;padding: 20px;text-align: center;";
        var msgBoxButtonStyle = "margin: 20px;";

        var msgDiv = "";

        if (title == null) {
            title = "Confirm";
        }

        if (onYes == null) {
            onYes = "";
        }

        if (onNo == null) {
            onNo = "";
        }

        if (onCancel == null) {
            onCancel = "";
        }

        msgDiv += "<div id='msgboxDiv' style='" + msgBoxDivStyle + "'>";  // Covers the entire body to prevent any interaction with controls in the body.
        msgDiv += "<div id='msgboxContents' style='" + msgBoxContentsStyle + "'>";  // Contains the messagebox itself
        msgDiv += "<div id='msgboxTitle' style='" + msgBoxTitleStyle + "'>" + title + "</div>";
        msgDiv += "<div id='msgboxText' style='" + msgBoxTextStyle + "'>" + msg + "</div>";  // Contains the text of the message to be displayed.
        msgDiv += "<button id='answerYes' tabindex='1' style='" + msgBoxButtonStyle + "' accesskey='Y' onclick='document.body.removeChild(this.parentElement.parentElement);" + onYes + "'><u>Y</u>es</button>";
        msgDiv += "<button id='answerNo' tabindex='2' style='" + msgBoxButtonStyle + "' accesskey='N' onclick='document.body.removeChild(this.parentElement.parentElement);" + onNo + "'><u>N</u>o</button>";
        msgDiv += "<button id='answerCancel' tabindex='3' style='" + msgBoxButtonStyle + "' accesskey='C' onclick='document.body.removeChild(this.parentElement.parentElement);" + onCancel + "'><u>C</u>ancel</button>";
        msgDiv += "</div></div>";  // Closes the modalBox and modalDiv tags

        document.body.insertAdjacentHTML("afterbegin", msgDiv);

        // This next line is necessary so that the new elements can be referred to in the following JavaScript code.
        document.body.focus();

        // Intercept the tab key so that the user can't use it to get to the other controls on the page.
        document.getElementById('answerYes').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerNo').focus();return false;}}
        document.getElementById('answerNo').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerCancel').focus();return false;}}
        document.getElementById('answerCancel').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerYes').focus();return false;}}

        // Put the user's focus on the Yes button.
        document.getElementById('answerYes').focus();

    } catch (e) {
        JavaScriptError(e);
    }

}


/**************************************************************************************************/
/* Function JavaScriptError
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: JavaScript Error Object
/* Description: This function formats and uses the MsgBox function to display a JavaScript Error.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function JavaScriptError(e) {

    var msg = "";

    try {
        msg = e.name + "<br /><br />" + e.message + "<br /><br />" + e.stack;

    } catch (e) {
        msg = e.message;
    }

    try {
        MsgBox(msg, "JavaScript Error");

    } catch (e1) {
        alert(msg);
    }
}


/**************************************************************************************************/
/* Function jsonError
/* Parameters: JSON object with the following properties: errNumber, errMessage.
/*             The JSON object may have additional properties, but it will only use the errNumber
/*             and errMessage properties.
/* Description: This function formats and displays a JSON error.
/**************************************************************************************************/
function jsonError(err) {
    msg = "Error " + err.errNumber + "<br /><br />";
    msg += err.errMessage + "<br /><br />";
    MsgBox(msg, "Exception");
}

3
如果您可能随时“删除档案”,那么这个回答随时可能变得过时。 - Sildoreth
不错的尝试,但无法取代js confirm。它不能暂停活动以等待选择。 - webs

0

ModaliseJS,比tomloprodModal更轻量,并且与任何CSS兼容。

HTML:(如果您有自己的设计或使用bootstrap,请省略modalise.css)

<!DOCTYPE html>
<html>
<head>
    <title>Modal example</title>
    <link href="../../dist/modalise.css" rel="stylesheet">
    <script src="../../dist/modalise.js" type="text/javascript">
    </script>
    <script src="app.js" type="text/javascript">
    </script>
</head>
<body>
    <h1>Example modal 1</h1><button id="openModal">Show the modal</button>
    <div class="mdl mdl-fadein" id="exampleModal">
        <div class="mdl-content mdl-slidein">
            <center>
                <div class="mdl-header mdl-band-primary">
                    <span class="close">X</span>
                    <h2>Example modal</h2>
                </div>
                <div class="mdl-body">
                    <h3>Content modal</h3>
                </div>
                <div class="mdl-footer mdl-band-primary">
                    <button class="confirm" onclick="return false">Do
                    thing</button><button class="cancel" onclick=
                    "return false">Cancel the thing</button>
                </div>
            </center>
        </div>
    </div>
</body>
</html>

代码:

var myModal = {}

window.onload = function(){
  // It is one of the button Modalise will attach the Show event.
  // Note that you can use Modalise without the events, by omitting the .attach() function.
  // Then, you can use show() or hide() to use it manually without overload. 
  var btnOpen = document.getElementById('openModal');

  // Modalise(id, options);
  myModal = new Modalise('exampleModal', {
      btnsOpen : [btnOpen]
    })
    .attach()
    .on('onShow', console.log)
    .on('onConfirm', console.log)
    .on('onHide', console.log);
}

喜欢你的解决方案,但 GPL 许可证在我的使用情况下因法律原因成为了一个障碍。如果是 MIT 许可证,我会使用这个。 - Carnix
那是很久以前的事了,我将许可证更改为MIT,因为这使一切都变得微不足道 ;) 此外,这已经是7年前的事情了,今天有其他选项,通常嵌入在您的框架中。 - Alexis Paques

0

我不是 JavaScript 的粉丝,但这里有一个漂亮的跨浏览器模态窗口,它使用普通的 HTML 和简单的 JavaScript 来实现你所需要的功能:

  1. 此代码不需要 JQuery 或 Bootstrap
  2. 此代码适用于新旧浏览器,包括Internet Explorer 9
  3. 此代码使用普通的、老式的 JavaScript,在几乎所有浏览器中都能工作!
  4. 此代码使用新的 HTML5 <dialog> 元素,并为不了解此元素的旧浏览器提供了漂亮简单的回退代码(在2021年,这样的浏览器还有很多!)

只需将下面的 HTML 和 JavaScript 代码块粘贴并根据需要进行自定义。

HTML(注意:CSS 是内联添加的,因此请将其移至您的样式表中)

<div id="dialogbox_alt" role="dialog" aria-label="Alternate Dialog">
  <dialog id="dialogbox" role="dialog" aria-label="Dialog" style=" display:none; width: 20em; max-width: 50%; padding: 1em; background-color: #fff; border: 2px solid #999; border-radius: .5em; /* center all dialogs */ position: fixed; top: 50%; left: 50%; margin-left: -10em; margin-top: -5em; z-index: 99; /* create background screen */ box-shadow: 0 0 0 9999px rgba(0,0,0,0.6); ">
    <form id="formdialog1" action"#" method="dialog" style="position:relative;width:100%;height:100%;padding:0;margin:0;">
    <span id="dialogcloser" style="display:inline-block;cursor:pointer;padding:.2em;position:absolute;top:-5px;right:-5px;">X</span>
    <div style="padding:1em;">
    <p>
        <label for="animals1">Choose an Animal:</label>
        <select id="animals1" name="animals1" required="required" aria-required="true" role="listbox" aria-label="List of Animals" tabindex="0">
        <option value="" selected="selected">- choose an animal -</option>
        <option value="elephant">Elephant</option>
        <option value="zebra">Zebra</option>
        <option value="lion">Lion</option>
        </select>
      </p>
      <p>
        <button type="submit" name="dialogconfirm" value="confirm">Confirm</button>
      </p>
      </div>
    </form>
  </dialog>
</div>
<button id="dialogopener" type="button">Open A Dialog Box</button> 

JAVASCRIPT(拥有所有跨浏览器的好东西,支持IE9)

<script type="text/javascript">
// ================ CROSS-BROWSER DIALOG BOX SCRIPT ===============
// This window.onload" version works in very old browsers. Do not use 'addEventListener'!
    window.onload = function () {

    // Make sure these element 'ids' match the open and close button and image in your HTML!
    var DIALOG_BOX = 'dialogbox';
    var DIALOG_BOX_ALT = 'dialogbox_alt';
    var DIALOG_OPENER = 'dialogopener';
    var DIALOG_CLOSER = 'dialogcloser';

    if (document.getElementById(DIALOG_BOX) && document.getElementById(DIALOG_BOX_ALT)) {
        if (document.getElementById(DIALOG_OPENER)) {
            if (document.getElementById(DIALOG_CLOSER)) {

                var dialogbox = document.getElementById(DIALOG_BOX);
                var dialogbox_alt = document.getElementById(DIALOG_BOX_ALT);
                var dialogopener = document.getElementById(DIALOG_OPENER);
                var dialogcloser = document.getElementById(DIALOG_CLOSER);

                // OPEN DIALOG : cross-browser script
                if (dialogopener.addEventListener) { // W3C DOM
                    dialogopener.addEventListener('click', function () {
                        dialogbox.style.display = "block";
                        if (typeof dialogbox.showModal === "function") {
                            dialogbox.showModal();
                        }
                    }, false);
                } else if (dialogopener.attachEvent) { // IE 5-8 DOM
                    dialogbox_alt.style.cssText = 'position: absolute ;top: -9999px;left: -9999px;';// hide the box on first page view
                    dialogopener.attachEvent('onclick', function () {
                        // WARNING: All older non-HTML5 supporting browser will not parse the 'dialog' element.
                        // So, we reveal a plain "div" element instead.
                        // For IE 5-6
                        dialogbox_alt.style.cssText = 'display:block;overflow:auto;width:300px;height:150px;padding:10px;background-color: #ffffff;border:2px solid #999999;z-index: 99;position:fixed;top:40%;left:40%;';
                        // For IE 7-8
                        dialogbox_alt.setAttribute('style','display:block;width:20em;height:auto;max-width: 50%;padding: 1em;background-color: #fff;border: 2px solid #999999;z-index: 99;border-radius: .5em;position: fixed;top: 50%;left: 50%;margin-left: -10em;margin-top: -5em;');
                    });
                } else { // MISC DOM
                    dialogbox_alt.style.cssText = 'position: absolute ;top: -9999px;left: -9999px;';
                    dialogopener["onclick"] = function () {
                        dialogbox_alt.style.cssText = 'display:block;overflow:auto;width:300px;height:150px;padding:10px;background-color: #ffffff;border:2px solid #999999;z-index: 99;position:fixed;top:40%;left:40%;';
                    };
                };

                // CLOSE DIALOG : cross-browser script
                if (dialogcloser.addEventListener) { // W3C DOM
                    dialogcloser.addEventListener('click', function () {
                        dialogbox.style.display = "none";
                        if (typeof dialogbox.showModal === "function") {
                            dialogbox.close();
                        }
                    }, false);
                } else if (dialogcloser.attachEvent) { // IE 5-8 DOM
                    dialogcloser.attachEvent('onclick', function () {
                        // WARNING: All older non-HTML5 supporting browser will not parse the 'dialog' element.
                        // So, we reveal a plain "div" element instead.
                        dialogbox_alt.style.cssText = 'position: absolute ;top: -9999px;left: -9999px;';
                    });
                } else { // MISC DOM
                    dialogcloser["onclick"] = function () {
                        dialogbox_alt.style.cssText = 'position: absolute ;top: -9999px;left: -9999px;';
                    };
                };

            } else {
                alert('The "dialogcloser" element is not found by a JavaScript function!\n\nMake sure the "dialogcloser" element id value matches\nthe JavaScript "DIALOG_CLOSER" variable value.');
            };
        } else {
            alert('The "dialogopener" element is not found by a JavaScript function!\n\nMake sure the "dialogopener" element id value matches\nthe JavaScript "DIALOG_OPENER" variable value.');
        };
    } else {
        alert('The "dialogbox" element(s) are not found by a JavaScript function!\n\nMake sure the "dialogbox" element id value matches\nthe JavaScript "DIALOG_BOX" variable value.');
    };

};
// ================================================================
</script>

关于Internet Explorer浏览器支持的注意事项:

  1. IE 10-11:在背景下正常运行
  2. IE 9:正常运行但没有背景
  3. IE 7-8:正常运行但没有背景和圆角边框
  4. IE 4-6:对话框出现在其父块内,但是完全功能正常

0
我创建了一个名为Msg的库,它可以轻松创建模态窗口。它有很多选项和事件,可以创建不同类型的模态窗口。一切都可以通过CSS进行自定义。它还是一个单文件,无需导入CSS文件。

-2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接