Div作为模态 - javascript

iho*_*rko 1 html javascript background modal-dialog

我需要一个JavaScript,它在屏幕中央显示隐藏的div作为模态,带有像jquery对话框一样的深色背景!

例:

<div id='divToShow' style='display:none'>

Here is the content of the div that should be shown as modal on the center of the page!

</div>
Run Code Online (Sandbox Code Playgroud)

谁可以帮忙?谢谢

mir*_*sif 5

一个简单的模态弹出div或对话框可以通过CSS属性和一点点jQuery来完成.基本思路很简单:

  • 1.创建一个半透明背景的div,并在点击时将其显示在内容页面的顶部.
  • 2.在半透明调光/隐藏div的顶部显示弹出div或警告div.
  • 所以我们需要三个div:

  • 内容(网站的主要内容).
  • 隐藏(调暗内容).
  • popup_box(要显示的模态div).

    首先让我们定义CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    
    Run Code Online (Sandbox Code Playgroud)

    重要的是我们将hider div的z-index设置为低于pop_up框,因为我们要在顶部显示popup_box.
    以下是java脚本:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    
    Run Code Online (Sandbox Code Playgroud)

    最后是HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    
    Run Code Online (Sandbox Code Playgroud)

    我使用了jquery-1.4.1.min.js www.jquery.com/download并在Firefox中测试了代码.希望这可以帮助.