javascript01-div居中的兼容问题,发一个奇怪的代码,可能是我没有理解精髓吧。...
天做项目需要用的一个div居中,下面一个模态层的问题,我写了个代码,大概分离出来如下。
< html xmlns = "http://www.w3.org/1999/xhtml" >
|
< head runat = "server" >
|
< title ></ title >
|
< style type = "text/css" >
|
div
|
{
|
width: 200px;
|
height: 300px;
|
background: red;
|
border: 1px solid black;
|
}
|
</ style >
|
</ head >
|
< body >
|
< div >
|
</ div >
|
< div >
|
</ div >
|
< div id = "d" style = "position: absolute; width: 200px; height: 300px;" >
|
</ div >
|
< script type = "text/javascript" >
|
var pageWidth = 0;
|
var pageHeight = 0;
|
var left = "0px";
|
var top = "0px";
|
var divWidth = 0;
|
var divHeight = 0;
|
var d = document.getElementById("d");
|
if (d) {
|
// divWidth = (d.style.width.toString()).replace("px", "");
|
// divHeight = (d.style.height.toString()).replace("px", "");
|
divWidth = parseInt(d.style.width.toString());
|
divHeight = parseInt(d.style.height.toString());
|
}
|
if (document.compatMode == "CSS1Compat") {
|
pageWidth = parseInt(document.documentElement.clientWidth);
|
pageHeight = parseInt(document.documentElement.clientHeight);
|
} else {
|
pageWidth = parseInt(document.body.clientWidth);
|
pageHeight = parseInt(document.body.clientHeight);
|
}
|
left = ((pageWidth - divWidth) / 2).toString() + "px";
|
top = ((pageHeight - divHeight) / 2).toString()+"px";
|
d.style.left = left
|
d.style.top = ((pageHeight - divHeight) / 2).toString() + "px";//goog浏览器不得行????
|
d.innerHTML = "pageWidth:" + pageWidth + "< br /> pageHeight:" + pageHeight + "< br /> divWidth:" + divWidth
|
+ " < br />divHeight:" + divHeight + " < br />left:" + left + " < br />top:" + top;
|
</ script >
|
</ body >
|
</ html >
|
d.style.top = ((pageHeight - divHeight) / 2).toString() + "px";//goog浏览器不得行????
请注意这段代码,这个代码在IE,火狐,google浏览器下都没有问题,但是将这句改成
d.style.top = top;
google就错了。不知道什么原因?求解答。