關於彈出div層居中的問題及解決方法

彈出div層在做網站中用到的也不少,但是如何儘可能的做到兼容各個瀏覽器的各個版本,這可是個大問題了,相信這也是大家頭疼的問題。同一個方法在不同的瀏覽器得到的值是不同的,就拿document.documentElement.scrollTop來說吧。
ie下document.documentElement.scrollTop是不爲0的;
chrome下document.documentElement.scrollTop卻爲0;
同時,html頭部的聲明不同得到的值也是不一樣的,
比如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
或者
<!DOCTYPE html>
<html>
總之類似的問題多了去了。
下面給出一個相對比較兼容的div彈出層的解決方案:

<!DOCTYPE html>
<html>
<head runat="server">
    <title>sssssss</title>
    <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
    <style>
        body { height: 5000px; }
        .top-1 { height: 1000px; border: solid 1px red; }
        .top-1 { height: 500px; border: solid 1px red; }
        .box { position: fixed; left: 50%; top: 50%; display: none; border: 1px solid blue; width: 500px; height: 300px; }
    </style>
</head>
<body>
    <div id="box" class="box">
        ssssssssssss</div>
    <div class="top-1">
    </div>
    <input type="button" id="show_1" value="click" οnclick="showBox();" />
    <div class="top-2"></div>
    <input type="button" id="show_2" value="click" />
    <script type="text/javascript">
        //判斷是否是ie6,如果是ie6則設置box的position屬性爲absolute,並添加onscroll事件;
        //否則設置box的position屬性爲fixed
        //首先要設置box樣式position: fixed; left: 50%; top: 50%;
        function showBox() {
            var box = $("#box");
            box.show();
            if ($.browser.msie && $.browser.version == "6.0") {                
                setIe6Box();
                window.onscroll = function () {
                    setIe6Box();
                }
                function setIe6Box() {
                    var box_margin_top = document.documentElement.scrollTop - box.height() / 2 + "px";
                    var box_margin_left = document.documentElement.scrollLeft - box.width() / 2 + "px";
                    box.css({ "position": "absolute", "margin-top": box_margin_top, "margin-left": box_margin_left });
                }
            }
            else {
                box.css({ "margin-top": (-box.height() / 2 + "px"), "margin-left": (-box.width() / 2 + "px") });
            }
        }
    </script>
</body>
</html>
基於中國用戶大多數使用的是ie,這個解決方案也基本上夠用了。

發佈了40 篇原創文章 · 獲贊 57 · 訪問量 50萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章