首页 > 解决方案 > 从 getBoundingClientRect() 设置边距

问题描述

我创建了一个fixed始终显示在页面顶部的元素。

我想让它下面的元素与元素margin-top的高度相同,fixed这样它就不会覆盖其他元素。

但问题是,它不起作用resize

HTML

<body>
   <div class="fixedEl">
      
   </div>
   <div class="otherEl">
      
   </div>
</body?

CSS

.fixedEl{
  position: fixed;
  top: 0;
  width: 100%;
}

JS

const fixedEl = document.querySelector(".fixedEl");
const height = notif.getBoundingClientRect().height;
const otherEl = document.querySelector(".otherEl");

window.addEventListener("resize", () => {
  otherEl.style.marginTop = `${height}px`;
});

我的代码有问题吗?感谢任何帮助,谢谢。

标签: javascripthtmlcss

解决方案


我认为它工作正常。但是,resize 事件仅在您调整大小时触发,但不会在站点加载时自动触发。我补充说,如下所示。

const fixedEl = document.querySelector(".fixedEl");
// Changed from notif to fixedEl
const otherEl = document.querySelector(".otherEl");
let height = fixedEl.getBoundingClientRect().height;
// We have no resize at the beginning, so we init the height
otherEl.style.marginTop = `${height}px`;

window.addEventListener("resize", () => {
  height = fixedEl.getBoundingClientRect().height;
  otherEl.style.marginTop = `${height}px`;
});
.fixedEl{
  position: fixed;
  top: 0;
  width: 100%;
}

div {
  border: 1px gray solid;
}
<body>
   <div class="fixedEl">
      foo barfoo barfoo barfoo barfoo barfoo bar
   </div>
   <div class="otherEl">
      bar
   </div>
</body>


推荐阅读