[英]How to get values of left/right/top/bottom properties in pixel using javascript?
我需要在px
中获取#test
的left / right / top / bottom属性。 我的js代码将属性值设置为auto
。 如何获取px
的值?
<div id="test">
<p>Dummy text</p>
</div>
#test{
position: absolute;
}
window.onload = function(){
var test = document.getElementById("test");
var left = window.getComputedStyle(test).getPropertyValue("left");
console.log(left); // auto
};
使用offsetLeft
代替
test.offsetLeft
window.onload = function(){ var test = document.getElementById("test"); document.write(test.offsetLeft); // auto };
#test{ position: absolute; }
<div id="test"> <p>Dummy text</p> </div>
使用此代码
window.onload = function(){ var test = document.getElementById("test"); var left = test.offsetLeft; var right = test.offsetWidth - left; var top = test.offsetTop; var bottom = test.offsetHeight - top; document.write("Left:" + left + "//"); document.write("Right:" + right + "//"); document.write("Top:" + top + "//"); document.write("Bottom:" + bottom); };
#test{ position: absolute; }
<div id="test"> <p>Dummy text</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.