2015-12-14 41 views
3

我一直在想弄清楚這個JQuery代碼的純JavaScript版本的正確語法。純jQuery相當於jQuery的作業

$('body').css('margin-bottom', $('footer').height()); 

到目前爲止,我所擁有的是:

var body = document.getElementById('#body'); 
var footer = document.getElementById('#footer'); 

body.style.marginBottom = footer.style.height; 

如果定義在JavaScript頁腳高度此任務纔有效。

我知道這個問題How to make a pure javascript .css() function using variable variables [duplicate]和它相似的問題,但仍是無法得到它正確的。我知道我可以使用JQuery,但是我並沒有看到加載整個庫來執行非常簡單的事情的價值。

預先感謝您。

+0

你試過footer.offsetHeight? https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight – AtheistP3ace

+1

你有沒有嘗試刪除前面的哈希ID? getElementById('body') –

+0

或將'document.getElementById('#body')'改爲'document.querySelector('#body')' –

回答

1

打開JavaScript控制檯並鍵入console.log(document.body.style)以查看document.body具有的所有樣式屬性。另外我認爲它是document.body而不僅僅是body

身體似乎有以下邊距屬性:

margin: "" 
marginBottom: "" 
marginLeft: "" 
marginRight: "" 
marginTop: "" 

所以document.body.style.marginBottom = '15px'應該例如工作。請記住,您必須指定單位,如px

0

使用的offsetHeight:

body.style.marginBottom = footer.offsetHeight;