使用JavaScript读取html / body标签margin-top

Using JavaScript to read html / body tag margin-top

本文关键字:body 标签 margin-top html JavaScript 读取 使用      更新时间:2023-09-26

我正试图从<html><body>标签中读取"marginTop"样式属性。Chrome开发工具显示margin-top设置通过在html内的CSS:

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

然而,当我尝试这样做时:

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

在两种情况下我都得到空字符串。

jQuery的offset()函数可以正确检测页边距。不幸的是,在这种情况下我不能使用jQuery,它必须是纯JavaScript。

如果有人能提供一些关于如何读取html和body元素的top margin属性的见解,我将不胜感激。

你可以这样解决:

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');