js實(shí)現(xiàn)div彈出層的方法

字號(hào):


    話說(shuō)現(xiàn)在各種插件出來(lái)了要實(shí)現(xiàn)彈出層真是太簡(jiǎn)單了,但個(gè)人有時(shí)覺(jué)得那些插件不實(shí)用經(jīng)常會(huì)找一些純js原生態(tài)的東西,下面來(lái)給各位分享一個(gè)原生太js div彈出層實(shí)例,有需要的朋友可一起看看。
    這個(gè)不用多說(shuō)了,直接貼代碼吧.有碼有注釋:
    代碼如下:
    /*
    * 彈出DIV層
    */
    function showDiv()
    {
    var Idiv = document.getElementById("Idiv");
    var mou_head = document.getElementById('mou_head');
    Idiv.style.display = "block";
    //以下部分要將彈出層居中顯示
    Idiv.style.left=(document.documentElement.clientWidth-Idiv.clientWidth)/2+document.documentElement.scrollLeft+"px";
    Idiv.style.top =(document.documentElement.clientHeight-Idiv.clientHeight)/2+document.documentElement.scrollTop-50+"px";
    //以下部分使整個(gè)頁(yè)面至灰不可點(diǎn)擊
    var procbg = document.createElement("div"); //首先創(chuàng)建一個(gè)div
    procbg.setAttribute("id","mybg"); //定義該div的id
    procbg.style.background = "#000000";
    procbg.style.width = "100%";
    procbg.style.height = "100%";
    procbg.style.position = "fixed";
    procbg.style.top = "0";
    procbg.style.left = "0";
    procbg.style.zIndex = "500";
    procbg.style.opacity = "0.6";
    procbg.style.filter = "Alpha(opacity=70)";
    //背景層加入頁(yè)面
    document.body.appendChild(procbg);
    document.body.style.overflow = "hidden"; //取消滾動(dòng)條
    //以下部分實(shí)現(xiàn)彈出層的拖拽效果
    var posX;
    var posY;
    mou_head.onmousedown=function(e)
    {
    if(!e) e = window.event; //IE
    posX = e.clientX - parseInt(Idiv.style.left);
    posY = e.clientY - parseInt(Idiv.style.top);
    document.onmousemove = mousemove;
    }
    document.onmouseup = function()
    {
    document.onmousemove = null;
    }
    function mousemove(ev)
    {
    if(ev==null) ev = window.event;//IE
    Idiv.style.left = (ev.clientX - posX) + "px";
    Idiv.style.top = (ev.clientY - posY) + "px";
    }
    }
    function closeDiv() //關(guān)閉彈出層
    {
    var Idiv=document.getElementById("Idiv");
    Idiv.style.display="none";
    document.body.style.overflow = "auto"; //恢復(fù)頁(yè)面滾動(dòng)條
    var body = document.getElementsByTagName("body");
    var mybg = document.getElementById("mybg");
    body[0].removeChild(mybg);
    }
    <!--彈出層開始-->
    <div id="Idiv">
    <div id="mou_head"100px; height=10px;z-index:1001; position:absolute;">這個(gè)是用來(lái)實(shí)現(xiàn)拖層</div>
    <input type="button" value="關(guān)閉" onclick="closeDiv();" />
    </div>
    <!--結(jié)束-->
    至于一些美化效果,大家可以自己去修修改改了。