繁体   English   中英

如何使用javascript获取像素的left / right / top / bottom属性值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM