我正在尝试创建一个图像叠加功能,将图像推高其自高度度的一半。
到目前为止,我已经能够为所有元素调整 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 使用每个元素自己的高度将 margin-bottom 添加到具有类的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826136/