使用JavaScript读取html / body标签页边距 [英] Using JavaScript to read html / body tag margin-top
本文介绍了使用JavaScript读取html / body标签页边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从< html>
和< body>
中读取marginTop >标签。 Chrome开发者工具在HTML CSS中显示margin-top:
< style type =text / cssmedia = 屏幕 >
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元素。
解决方案
您可以使用以下方法解决这个问题:
var element = document.getElementsByTagName('html')[0],
style = window.getComputedStyle(element),
marginTop = style.getPropertyValue('边距');
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');
这篇关于使用JavaScript读取html / body标签页边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文