javascript - 如何使用 Javascript 使用每个元素自己的高度将 margin-bottom 添加到具有类的所有元素?

标签 javascript css

我正在尝试创建一个图像叠加功能,将图像推高其自高度度的一半。

到目前为止,我已经能够为所有元素调整 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/

相关文章:

javascript - 通知弹出窗口不会出现在 chrome 中

javascript - 视频标签后,触摸事件在 iPad 上停止工作

javascript - 从 Angular http 调用加载数据和背景图像后

javascript - jQuery fadeIn() 未达到完全不透明

javascript - 将一个 ES6 类分解成多个文件

css - 当Chrome DevTools中的css类名称只有星号时,星号是什么意思?

html - 仅限 Safari - 菜单出现在错误的位置

javascript - 将文本放入固定大小的 div

html - 向下滚动时,如何使其与我的视频重叠?

javascript - 通过评估 innerHTML 更改类