2012-02-04 10 views
1

は、私はこのように割り当てることができます。offsetHeightをstyle.topに割り当てることはできますか? JavaScriptで

var tempHeight = document.getElementById("header").offsetHeight; 
document.getElementById("content").style.top = tempHeight; 

スクリプト上で実行した後、DIV "コンテンツ" とは、 "トップ" propery = tempHeightを持っているのだろうか? 私はしようとしましたが、それは動作しません、任意の提案? ありがとう!

答えて

1

あなただけあなたがstyle.top文の最後に+ 'px'またはいくつかのユニットを追加する必要がユニット

document.getElementById("content").style.top = String(tempHeight) + "px"; 
+0

本当にありがとう、私は新しいJavascriptに、何かリンクtempHeight.toStringを試しましたが、うまくいきませんでした。ありがとうございましたString()関数:D – Leo

+1

'Number'は' String'と連結すると自動的に 'String'に変換されます。したがって、 'String'をキャストする必要はありません。 – Trevor

+0

'console.log(typeof tempHeight)//数値' 'console.log(typeof(tempHeight + 'px'))//文字列' – Trevor

0

top CSSプロパティは、値とともにユニットを必要とします。 pxが動作するはずの追加:

document.getElementById("content").style.top = tempHeight + "px"; 
+0

を設定しておく必要があります正しい方法があり、私が試したが、それはうまくいきませんでしたFlambinoの – Leo

0

を必要としています。

はまた、#contentpositionスタイルが

http://jsfiddle.net/BshuC/

CSS

#header { 
     height: 200px; 
} 
#content { position: absolute; } 

JS

var tempHeight = document.getElementById("header").offsetHeight; 
document.getElementById("content").style.top = tempHeight + 'px'; 
関連する問題