【问题标题】:Getting margin-top with obj.style.marginTop failed, but it worked if marginTop was set explicitly first使用 obj.style.marginTop 获取 margin-top 失败,但如果首先明确设置 marginTop,它就可以工作
【发布时间】:2016-04-01 02:53:52
【问题描述】:

请先查看这个问题:

document.body.style.marginTop returning blank string in JS

有几个可行的解决方案......然后是我的可行解决方案:

https://stackoverflow.com/a/34473070/2813224

总结:

尝试通过执行以下代码及其变体来获取 div 的 margin-top 值:

/*~~~~~~~~~~~~~~~~~~~[ Attempt 1 ]~~~~~~~~~~~~~~~~~~~~~~~~*/

alert(document.getElementById("testDiv").style.marginTop);

/*~~~~~~~~~~~~~~~~~~~[ Attempt 2 ]~~~~~~~~~~~~~~~~~~~~~~~~*/

var tDiv = document.getElementById('testDiv');
var tMgn = tDiv.style.marginTop;
alert(tMgn);

/*~~~~~~~~~~~~~~~~~~~[ Attempt 3 ]~~~~~~~~~~~~~~~~~~~~~~~~*/

var tDiv = document.querySelector('testDiv');
alert(tDiv.style.marginTop);

/*~~~~~~~~~~~~~~~~~~~[ Attempt 4 ]~~~~~~~~~~~~~~~~~~~~~~~~*/

function mTop() {
   var tDiv = document.getElementById('testDiv');
   var tMgn = tDiv.style.marginTop;
   alert(tMgn);
}
mTop();

这些组合的共同点是.style.marginTop。此后不久,操作员的问题是answered

我的问题是:

我不知道为什么,但我首先通过 JS 显式分配 margin-top 使其工作。我从来不需要首先设置样式值来获取样式值,特别是如果它已经由 CSS 设置。为什么会这样简单:

alert(document.getElementById("testDiv").style.marginTop);  

不起作用,但这样做:

document.getElementById("testDiv").style.marginTop = "50px";
alert(document.getElementById("testDiv").style.marginTop);

当 CSS 已经存在时:

#testDiv { margin-top: 50px; }

?

我的工作答案片段:

document.getElementById("testDiv").style.marginTop = '50px';
document.body.style.marginTop = '100px';
alert(document.getElementById("testDiv").style.marginTop);
alert(document.body.style.marginTop);
body {
  margin-top: 100px;
}
#testDiv {
  margin-top: 50px;
}
hi!

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

【问题讨论】:

  • 可能是因为 element.style 只返回 inline 样式。对于在外部样式表中设置的样式,您需要 getComputedStyle 而不是
  • 感谢您的输入,@adeneo 好的,我明白了,但是当 element.style 预先分配值时,块元素的 element.style 怎么可能返回正确的值?跨度>
  • element.style 设置内联样式,并再次使用element.style 获取样式only 获取内联样式。
  • 所以如果我有一列 div 并且我使用 element.style 设置其中一个的边距,那么该 div 会变成内联并破坏布局?一定要记住这一点,谢谢@adeneo

标签: javascript html css


【解决方案1】:

您需要使用window.getComputedStyle 来获取计算出来的样式,但不是通过JavaScript 设置的,因为HTMLElement.style 只能获取内联样式。

语法是:

var style = window.getComputedStyle(element[, pseudoElt]);

所以在你的情况下,它应该是:

var elem = document.getElementById("testDiv");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("margin-top");
document.getElementById("output").innerHTML = theCSSprop;

【讨论】:

  • 您好,感谢您抽出宝贵时间回答。当我问 adeneo 时,当我使用HTMLElement.style 将值设置为一个块时,我使用HTMLElement.style 得到了正确的值。这怎么可能?
  • 这么简单?我认为这套、get 和 forget 可以让我省去很多麻烦,谢谢,先生。
  • 先生,也祝您圣诞快乐。
猜你喜欢
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
相关资源
最近更新 更多