请先查看此问题:
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
。运算符(operator)的问题是 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>
最佳答案
您需要使用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;
关于javascript - 使用 obj.style.marginTop 获取 margin-top 失败,但如果首先显式设置 marginTop 则有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34473495/