为什么 marginTop 在设置后会发生变化?



我通过javascript为testdiv设置了marginTop='-1794557px'
但是当我使用相同的方法读取marginTop时,得到-1794560px。
此问题只发生在火狐浏览器上。正常吗?

var x="-1794557px";
document.getElementById("test").style.marginTop=x;
console.log('document.getElementById("test").style.marginTop=' + document.getElementById("test").style.marginTop);
document.getElementById("rst").innerHTML=document.getElementById("test").style.marginTop;
<div id="test" style="margin-top: 0px; background-color: #cccccc;">123</div>
<div style="position: absolute; top: 10px; left: 10px;">test margin-top: <span id="rst"></span></div>

尝试使用 element.offsetTop 代替,它似乎给出了更准确的结果,请查看代码段,或使用 element.getComputedStyle(p(

var x=-1794557;
document.getElementById("test").style.marginTop=x + "px";
var comp = getComputedStyle(document.getElementById("test")).marginTop
console.log('document.getElementById("test").style.marginTop=' + document.getElementById("test").style.marginTop, "actual margin:",document.getElementById("test").offsetTop, " computed style: ", comp.toString());
document.getElementById("rst").innerHTML=document.getElementById("test").style.marginTop + ", but the actual marginTop is really its offsetTop: " + document.getElementById("test").offsetTop + " even though that's a bit off, so try the computed style: " + comp;
<div id="test" style="margin-top: 0px; background-color: #cccccc;">123</div>
<div style="position: absolute; top: 10px; left: 10px;">test margin-top: <span id="rst"></span></div>

最新更新