javascript - 从 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`;
});
我的代码有问题吗?感谢任何帮助,谢谢。
解决方案
我认为它工作正常。但是,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>
推荐阅读
- javascript - Api 没有使用 react-redux
- flutter - Flutter 圆角矩形中的阴影
- arrays - 理解 awk 中的 IN 语句
- java - 如何使用 Payara Micro Bundle 将包列入白名单?
- r - R / Rvest / RSelenium:从 JS 站点抓取数据
- java - 我们什么时候使用堆栈
st = 新堆栈 (); 以及何时使用 Stack st = new Stack();? - javascript - 直接访问时,对象中的数组返回为未定义
- c# - 如何限制 Y 轴上的旋转,以使玩家无法在 Unity 中连续旋转相机
- excel - 搜索列名并复制数据
- cypress - 在柏树中存储变量以供重用