首页 > 解决方案 > 图像右边界到图像父 div 右边界的距离

问题描述

我想确定从图像 2 的右边界到图像父 div 的右边界的距离。

//The images will be aligned horizontally as in the image bellow
<div class = "parent-div">
    <img src "img01.jpg" />
    <img src "img02.jpg" />
    <img src "img03.jpg" />
    <img src "img04.jpg" />
    <img src "img05.jpg" />
</div>

我使用 CSS 来指定图像和父 div 的宽度,如下所示:

.parent-div{
    width: 400px;
    overflow: hidden;
}

.parent-div > img{
    width:100px;
}

下图示例,在 JQuery 或 JavaScript 中,从图像 2 的右边框到父 div 的右边框的距离是多少? 在此处输入图像描述

标签: javascriptjquery

解决方案


文档中所述Element.getBoundingClientRect()将获取元素相对于视口的位置,以及其他一些值,例如它自己的宽度和高度。使用后者,您可以获取容器的宽度和高度。

然后,获取子图像的值,您可以计算该值。

var containerEl = document.querySelector('.parent-div');
var containerElRect = containerEl.getBoundingClientRect();
var containerElWidth = containerElRect.width;

// This selects all img elements
var imgElements = containerEl.querySelectorAll('img');

// This selects the second image
var imgEl = imgElements[1];
var imgElRect = imgEl.getBoundingClientRect();
var imgElWidth = imgElRect.width;

// This is the offset from the left border of the image to the left border of the container
var imgElOffsetLeft = imgEl.offsetLeft;

// Calculate the value you search for:
var theDistance = containerElWidth - imgElWidth - imgElOffsetLeft;

console.log(theDistance);
.parent-div {
  /* This is important for `imgEl.offsetLeft` to work! 
  The nearest positioned parent is looked for with offsetParent. */
  position: relative;
  width: 400px;
  white-space: nowrap;
  border: 1px solid red;
  
  /* Only to kill spaces between images */
  font-size: 0;
  overflow-y: scroll;
}

.parent-div > img {
  width: 100px;
}
<div class="parent-div">
  <img src="https://picsum.photos/100/100" />
  <img src="https://picsum.photos/100/100" />
  <img src="https://picsum.photos/100/100" />
  <img src="https://picsum.photos/100/100" />
  <img src="https://picsum.photos/100/100" />
</div>


推荐阅读