关于弹出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,这个解决方案也基本上够用了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值