Pure javascript equivalent to jquery assignment

时间:2015-12-14 18:13:13

标签: javascript jquery html css

I've been trying to figure out the proper syntax for the pure JavaScript version of this JQuery code.

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

So far what I have is:

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

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

This assignment only works if I define the footer height in JavaScript.

I'm aware of this question How to make a pure javascript .css() function using variable variables [duplicate] and the questions similar to it, but still am unable to get it correct. I know I could just use JQuery, but I don't see the value in loading a whole library to do very simple things.

Thank you in advance.

2 个答案:

答案 0 :(得分:1)

打开JavaScript控制台并输入console.log(document.body.style)以查看document.body具有的所有样式属性。我认为它是document.body而不只是body

Body似乎有以下边距属性:

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

所以document.body.style.marginBottom = '15px'应该起作用。请记住,您必须指定单位,例如px

答案 1 :(得分:0)

使用offsetHeight:

body.style.marginBottom = footer.offsetHeight;