javascript - 如何使用 Javascript 使用每个元素自己的高度将边距底部添加到具有类的所有元素?
问题描述
我正在尝试创建一个图像叠加功能,将图像推高其自身高度的一半。
到目前为止,我已经能够调整所有元素的 CSS,但我想为每个元素添加一个 marginBottom,它是它自己高度的一半。
function adjustMarginBottom() {
const x = document.getElementsByClassName("example");
let i;
for (i = 0; i < x.length; i++) {
//I think this line should look something like this, but I'm still trying to work it out.
x[i].style.marginBottom = x[i].height - 50%;
}
}
任何建议都非常感谢!
解决方案
看一看:
function marginBottom() {
const x = document.querySelectorAll('.example');
x.forEach(img => {
const heightImg = img.height / 2;
console.log(heightImg);
img.style.marginBottom = `${heightImg}px`;
});
}
window.addEventListener('load', marginBottom);
<div>
<img class="example" src="https://fakeimg.pl/250x100/ff0000/">
</div>
<div>
<img class="example" src="https://fakeimg.pl/250x100/000/">
</div>
<div>
<img class="example" src="https://fakeimg.pl/250x100/ececec/">
</div>
推荐阅读
- javascript - JavaScript 说 10 低于 9
- python - Python“尝试除外”阻止继续使用普通代码
- java - 给定 IP 的 Spring Security 自动授权
- c# - 将 ASP.NET MVC 应用程序部署到服务器后的水晶报表问题
- spring - 无法在 eclipse photon 中创建 maven 项目
- matlab - 如何在 MATLAB 中更改 RGB 图像的像素值?
- vba - 我需要实现什么接口以允许在用 delphi 编写的 COM 对象上在 VBA 中使用 ForEach?
- bash - 是否可以在 Makefile 中设置环境变量 - 之后使用
- c# - 从ajax传递参数和模型
- javascript - 做一个扩大的圈子,在规模上揭示内容背后