js弹出div 统制div在窗口中的位置 居中

js弹出div 控制div在窗口中的位置 居中

div代码

 

<!-- 修改个人信息失败弹出div -->
    <div class="puw" display: none;"
        id="editUserFail" align="center">
        <div class="puw_title">
            <div class="puw_title_bt">修改个人信息</div>
            <div class="puw_close"></div>
        </div>
        <div class="puw_part">
            <div class="puw_icon">
                <img src="${ path}/images/delete.png" />
            </div>
            <div class="puw_text">修改失败</div>
            <div class="puw_btn">
                <a href="javascript:" onclick="closeDiv('editUserFail');"
                    class="btn">确定</a>
            </div>
        </div>
    </div>

 

 

js代码

 

 

第一种实现:

 

var editUserFailId = $("#editUserFail");
editUserFailId.show().css({"zIndex":"150","position":"absolute"});
center(editUserFailId);

 

 

 

function center(divId){
        var windowWidth = document.documentElement.clientWidth;
        //alert('窗口宽: '+windowWidth);
        var windowHeight = document.documentElement.clientHeight;
        //alert('窗口高: '+windowHeight);
        var popupHeight = $(divId).height();
        //alert('div高: '+popupHeight);
        var popupWidth = $(divId).width();
       
        //alert('div宽: '+popupWidth);
       
        $(divId).css({
            'top':(windowHeight - popupHeight - 270)/2+$(document).scrollTop()+80,
            'left':(windowWidth - popupWidth)/2-45
        });
    }

 

 第二种实现   这种是看jquery的jAlert插件的源码

var top = (($(window).height() / 2) - ($("#editUserFail")
                    .outerHeight() / 2))
                    + $.alerts.verticalOffset;
            var left = (($(window).width() / 2) - ($("#editUserFail")
                    .outerWidth() / 2))
                    + $.alerts.horizontalOffset;
            if (top < 0)
                top = 0;
            if (left < 0)
                left = 0;

            // 如果是在IE6或为火狐浏览器下
            //if ($.browser.msie && parseInt($.browser.version) <= 6)
                //top = top + $(window).scrollTop();

            $("#editUserFail").css({
                top : top + 'px',
                left : left + 'px'
            });

 

第三种实现:

document.getElementById("editUserFail").style.top=(document.documentElement.scrollTop+
(document.documentElement.clientHeight-document.getElementById("editUserFail").offsetHeight)/2)+"px";
document.getElementById("editUserFail").style.left=(document.documentElement.scrollLeft+(document.documentElement.clientWidth-document.getElementById("editUserFail").offsetWidth)/2)+"px";