如您所知,在中clientLeft
返回边框PXs
,并且您知道clientLeft
和clientTop
,那么为什么clientRight
和clientButtom
在JavaScript中不存在?以及如何在JavaScript中获取Right
and buttom
Border?
您可以通过从元素的父元素的offsetWidth中减去元素的offsetWidth和offsetLeft来计算“ offsetRight”。同样,您可以通过从元素的父元素的offsetHeight中减去元素的offsetHeight和offsetTop来计算“ offsetBottom”。我对为什么只有offsetLeft和offsetTop的猜测是,一个元素相对于其原点定位:沿X和Y轴距其父对象的左上角的距离,默认值为(0,0)。因此,偏移会检索这两个坐标。
const square = document.getElementById("square");
const parent = document.getElementById("parent");
const offsetTop = square.offsetTop;
const offsetLeft = square.offsetLeft;
const offsetHeight = square.offsetHeight;
const offsetWidth = square.offsetWidth;
const parentWidth = parent.offsetWidth;
const parentHeight = parent.offsetHeight;
const offsetBottom = parentHeight - offsetHeight - offsetTop;
const offsetRight = parentWidth - offsetWidth - offsetLeft;
console.log("top:", offsetTop, "left:", offsetLeft,"right:", offsetRight, "bottom:", offsetBottom);
body{
margin: 0;
}
#parent {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
}
#square {
margin: 0 auto;
width: 100px;
height: 100px;
background-color: red;
}
<div id="parent">
<div id="square"></div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句