clientHeight无法使用JavaScript?

时间:2012-12-22 07:32:59

标签: javascript html

我正在学习JavaScript并创建了倒数计时器HTML页面,其中javascript代码似乎返回了正文的错误clientHeight。我想在身体的中间(垂直)显示我的倒计时HTML <div>,即使重新调整了浏览器的大小。请告诉我我错在哪里。

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CountDown Timer</title>
<script type="text/javascript" >
function countdown(){
    if(isNaN(document.getElementById("time").value))
    {
       document.getElementById("time").value = "Enter Valid Number";
       return;
    }
    else
    {       
       var i = document.getElementById("time").value;
       var j=setInterval(function (){document.getElementById("new").innerHTML = i; i--;
       if(i == -2){
         document.getElementById("new").innerHTML = "Welcome";   
         clearInterval(j);}},1000);
       }
    }

    function heightadjust(){
       document.getElementById("main1").style.top = ((document.body.clientHeight/2)+54).toString() + "px";
    }

</script>
</head>

<body onresize="heightadjust();" onload="heightadjust();">
<div style="margin:0 auto;" id="main1">
   <center>
     <div id="new" style="display:inline-block; padding:3px; font-size:60px; text-align:center; border:3px solid #000000; background-color:#CC3300; color:#FFFFFF; border-radius:6px;">Enter Time Below</div>
     <br />
     <input type="text" id="time" onfocus="this.value = ''; this.style.color = '#000000';" value="Enter Time here" style="color:#999999;" />
     <button onclick="countdown();" >Start</button>
   </center>
</div>

</body>
</html>

请给我一些提示,即使浏览器重新调整大小,如何保持<div>垂直居中。

1 个答案:

答案 0 :(得分:3)

你不需要JS。

#in_the_middle {
  position:fixed;
  left:50%;
  top:100%;
  width:200px;
  margin-left:-100px; /* MUST be equal to width * -0.5 */
  height:50px;
  margin-top:-25px; /* SHOULD equal height * -0.5, but can vary for different fx */
  line-height:50px; /* Remove if there may be more than one line inside */
}