弹出模态对话框并生成遮罩层

        做过web项目的朋友,大家都知道,有时候点击某一个按钮或者a标签时,需要弹出一个编辑框。在编辑框弹出来的时候, 页面其它地方是不允许点击的,直到这个编辑框关闭。

那么我们如何做出这样一个效果呢?

其实也不难。

      首先需要有一个编辑框对应的div,默认为隐藏状态,点击“编辑”时,设置为显示状态;点击编辑框上的关闭按钮时,又隐藏掉。此编辑框需要设置为绝对定位(position: absolute),以便显示在屏幕的固定位置。

      其次需要一个遮罩层,为全屏幕的,半透明状态。编辑框弹出时,显示遮罩层;编辑框消失时,隐藏遮罩层。

     直接上代码吧酷

  1. html代码
    <body>
        <div id="edit_mask" class="none"></div> <!--遮罩层-->
        <div>
            <input type="text" id="keyword">
            <a id="edit" href="javascript:void(0)">编辑</a>
        </div>
        <!--弹出编辑框-->
        <div class="none edit_popup">  
            <div class="title" >
                <a href="javascript:void(0)" class="btn_close">X</a>
            </div>
        </div>
        <script type="text/javascript"  src="{% static 'js/test/test.js' %}"></script>
    </body>
     
  2. css代码
    .none {
        display: none;
    }
    .edit_popup {
        z-index: 100;
        position: fixed;
        top: 100px;
        left: 100px;
        width: 300px;
        height: 300px;
        background-color: #2aabd2;
    }
    .edit_popup .title {
        height: 40px;
        position: relative;
    }
    .edit_popup .btn_close {
        position: absolute;
        right: 10px;
        top: 10px;
    }
    #edit_mask {
        position: fixed;
        top: 0;
        right:0;
        bottom:0;
        left:0;
        width:100%;
        height:100%;
        opacity: 0.4;
        background:rgb(0, 0, 0);
        z-index: 50;
    }
    a {
        text-decoration: none;
    }
     
  3. js代码
    function bindEvents() {
            $('#edit').on('click', edit);
            $('.btn_close').on('click', close_edit);
        }
        function edit() {
            var left = ($(document).width() - parseInt($('.edit_popup').css('width'))) / 2;
            $('.edit_popup').css('left', left + 'px');
            $('.edit_popup').removeClass('none');
            $('#edit_mask').removeClass('none');
        }
        function close_edit() {
            $('.edit_popup').addClass('none');
            $('#edit_mask').addClass('none');
        }
     这样一个简易的弹出框就做好了。这里大家可以看一下布局里的相对定位、绝对定位、自动算出编辑框的left值(根据div宽度和document的宽度计算)。

猜你喜欢

转载自chaoren3166gg.iteye.com/blog/2314160
今日推荐