简体   繁体   中英

Using JavaScript to read html / body tag margin-top

I'm trying to read "marginTop" style property from the <html> and <body> tags. Chrome developer tools shows margin-top as set via in-HTML CSS:

<style type="text/css" media="screen">
html { margin-top: 28px !important; }
* html body { margin-top: 28px !important; }
</style>

However, when I try something like this:

console.debug(document.getElementsByTagName('html')[0].style.marginTop);
console.debug(document.getElementsByTagName('body')[0].style.marginTop);

I get empty strings in both cases.

jQuery's offset() function detects margins correctly. Unfortunately, I cannot use jQuery in this case, it has to be pure JavaScript.

I would appreciate if someone could provide some insight on how I can read top margin property off the html and body elements.

You can solve it with:

var element = document.getElementsByTagName('html')[0],
    style = window.getComputedStyle(element),
    marginTop = style.getPropertyValue('margin-top');

jsFiddle

document已经有关于body元素的知识,因此:

window.getComputedStyle(document.body).getPropertyValue('margin-top');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM