2010-06-01 54 views
0

我有兩個div需要水平放置,取決於用戶屏幕的寬度。我已經在CSS中設置了垂直位置,我試圖用Javascript水平定位它們。使用Javascript定位DIV

我的div:

<div id="tl"> 
    blah blah 
</div> 
<div id="bl"> 
    blah blah 
</div> 

我的CSS:

#tl { 
position: absolute; 
top: -14px; 
right: 0; 
} 
#bl { 
position: absolute; 
bottom: 1px; 
right: 0; 
} 

我的javascript:

var tl = document.getElementById('tl'); 
var bl = document.getElementById('bl'); 
var wide = parseInt(screen.width); 
var nudge = wide*.86; 
nudge = nudge+21; 
tl = tl.style; 
tl.right = (parseInt(tl.right) + nudge); 
bl = bl.style; 
bl.right = (parseInt(bl.right) + nudge); 

但是......沒有任何反應。沒有錯誤,絕對沒有我的div的動作。 我在做什麼錯?誰能幫忙?

回答

1

jQuery讓這很容易http://jquery.com/

$("#t1").css({"right" : $("#t1").position().right+$(window).width()*0.86+21}); 
+1

我不知道,但並不需要追加 「PX」 字符串?即$(「#t1」).css(「right」,「400px」); ? – user347594 2010-06-01 02:58:49

+0

我一直在推遲學習JQuery ......但我想是時候了。 謝謝,我想我會試試這個。 – Polyonymy 2010-06-01 04:00:10

+0

jquery對無痛javascript開發至關重要 – rzzmttzz 2010-06-01 04:23:34

1

讓你的 '正確' 的內聯方式:

<div id="tl" style="right:0"> 
    blah blah 
</div> 
<div id="bl" style="right:0"> 
    blah blah 
</div> 
+0

沒有任何效果... – Polyonymy 2010-06-01 03:59:19

+0

將腳本作爲函數調用並調用或將腳本(不帶函數)放到相關元素的下面。 – 2010-06-01 05:12:28