javascript - 图像右边界到图像父 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;
}
解决方案
如文档中所述,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>
推荐阅读
- ios - 带有 EXIF 数据的 Swift base64 图像编码
- c# - 如何将数据从控制器传递到C#中的视图
- java - 由于线程处于 WAITING 和 TIMED_WAITING 状态,请求处于挂起状态
- c# - MVC 路由问题?
- python - 如何在python中的每一行之后打印一个小空格
- excel - 如何使用 SPLIT 函数在 VBA 中的用户窗体中搜索多个条目?
- c++ - cpp新手问题:错误:转换为'std :: array
::size_type {aka long unsigned int}' from 'int' 可能会改变结果的符号 - javascript - 命令 `yarn add react-native --exact` 失败
- javascript - 为什么我的代码返回数组的最后一个值,而不是返回每个项目的结果?
- java - Micronaut 和 JUnit 回滚