首页 > 解决方案 > 如何使用 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%;
        }
    }

任何建议都非常感谢!

标签: javascriptcss

解决方案


看一看:

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>


推荐阅读