我試圖定位頁面標題塊到HTML頁面顯示的右側,實際位置取決於可用窗口的寬度。有一個div包含一個圖像和一個div,其中包含一行文字「按鈕」。爲什麼我的javascript不能重新定位這個標題?
兩個div的有position: absolute
集,我想使用JavaScript函數來設置top
和left
當頁面加載。我明顯錯過了一些東西,因爲javascript對顯示沒有任何影響 - 位置總是從樣式表中獲取(默認零或實際值:我都試過)。
這是代碼,減少嘗試隔離問題。底部的警報似乎表明左值與我預期的一樣(在我的測試用例中爲890px),但實際位置(以及Firebug報告的值)爲630px。我已經在Firefox 4.0.1和Chrome 11上嘗試過,效果相同。
<body onload="javascript:positionHeaders()">
<div id="pageheader">
<div id="pageheader1a">
x
</div>
<div id="pageheader1b">
x
</div>
<div id="pageheader2a">
<img src="../images/memooirs2_320x58.png" class="nonhreflink"
onclick="prepareIndexDisplay()" />
</div>
<div id="pageheader2b">
<span class="smallbutton" onclick="processLogout()">Logout</span><span class="smallbutton" onclick="prepareHelp()">Help</span><span class="smallbutton" onclick="prepareTour()">Take a tour</span>
</div>
</div>
</body>
#pageheader {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 80px;
border-bottom: 1px solid rgb(50,50,50);
background-image: url("../images/headerbkg.png");
background-repeat: repeat-x;
background-position: top;
}
#pageheader1a {
position: absolute;
top: 0;
left: 0;
}
#pageheader1b {
position: absolute;
top: 63px;
left: 0;
}
#pageheader2a {
position: absolute;
top: 0;
left: 630px;
}
#pageheader2b {
position: absolute;
top: 63px;
left: 630px;
}
.smallbutton {
position: relative;
margin: 0 5px 0 5px;
border: 0;
padding: 0;
font-size: 0.8em;
font-family: Verdana,Geneva,Arial,Helvetica,sans-serif;
color: rgb(50,50,50);
}
function positionHeaders() {
var lWidth = 0, lHeight = 0;
if(typeof(window.innerWidth) == 'number') { //Non-IE
lWidth = window.innerWidth;
lHeight = window.innerHeight;
}
else if(document.documentElement && (document.documentElement.clientWidth ||
document.documentElement.clientHeight)) { //IE 6+ standards compliant mode
lWidth = document.documentElement.clientWidth;
lHeight = document.documentElement.clientHeight;
}
else if(document.body && (document.body.clientWidth ||
document.body.clientHeight)) { //IE 4 compatible
lWidth = document.body.clientWidth;
lHeight = document.body.clientHeight;
}
var z1 = String(lWidth - 550);
document.getElementById("pageheader2a").top = "0";
document.getElementById("pageheader2a").left = z1 + "px";
document.getElementById("pageheader2b").top = "63px";
document.getElementById("pageheader2b").left = z1 + "px";
alert("2bleft=" + document.getElementById("pageheader2b").left);
}
這可能只能用html和css來完成。如果JS是必要的,我會推薦jQuery,因爲代碼會更簡單。 – 2011-05-06 11:25:28