document.body.style.marginTop在JS中返回空字符串 [英] document.body.style.marginTop returning blank string in JS

查看:268
本文介绍了document.body.style.marginTop在JS中返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是[some elem] .style.maginTop会返回一个带元素上边距的字符串。

It was my understanding that [some elem].style.maginTop would return a string with the element's top margin.

相反,我总是得到一个空白串。我想在身体上使用它,但我也尝试过div,但这也不起作用。

Instead, I'm always getting a blank string. I want to use this with the body, but I also tried on a div, and that didn't work either.

console.log(document.body.style.marginTop); // logs ""
console.log(typeof(document.body.style.marginTop)); // logs "String"

var elem = document.getElementById("testDiv");
console.log(elem.style.marginTop); // logs ""

body {
    margin-top:100px;
}
#testDiv {
    margin-top:50px;
}

hi!

<div id="testDiv">test</div>

我不确定我做错了什么...有人有非jQuery解决方案吗?

I'm not sure what I'm doing wrong... Does anybody have a non-jQuery solution to this?

推荐答案

HTMLElement.style 仅返回内联样式:


HTMLElement.style属性返回一个CSSStyleDeclaration对象,该对象表示元素的样式属性

要从样式表访问样式,请使用 Window.getComputedStyle(element)

To access the styles from stylesheets use Window.getComputedStyle(element):


Window.getComputedStyle()方法在应用活动样式表并解析这些值可能包含的任何基本计算后,给出元素的所有CSS属性的值。

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.

var elem = document.getElementById("testDiv");
var style = window.getComputedStyle(elem);

//output
document.body.innerHTML = style.marginTop;

body {
    margin-top:100px;
}
#testDiv {
    margin-top:50px;
}

hi!

<div id="testDiv">test</div>

这篇关于document.body.style.marginTop在JS中返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆