您的位置:首页 > 其它

关于弹出div层居中的问题及解决方法

2012-04-03 12:55 411 查看
弹出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" onclick="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,这个解决方案也基本上够用了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: