gpt4 book ai didi

javascript - 如何将网页向下推以适合顶部栏

转载 作者:太空宇宙 更新时间:2023-11-04 09:21:40 25 4
gpt4 key购买 nike

有没有办法使用 javascript 测量 div 元素的高度?

这是我的情况:我在我的网站上创建了一个顶部固定位置栏,所以即使我向上/向下滚动页面,栏保持在顶部,但我的问题是栏覆盖网页,我想要的是栏将网页向下推到高度栏所以它们看起来像堆叠的,我设法通过固定高度来做到这一点,比如 50ox,我设置了 html 页面上边距并且它们看起来不错,当栏的高度发生变化时,例如在手机中查看相同的页面会出错,因为高度在移动设备上增加了栏的高度,但我设置的上边距仍然是 50,所以我需要一种方法来测量渲染 ti 时栏的实际高度并根据它调整页面。

最佳答案

如果您将顶部栏固定到位,您就不必担心它下面的内容实际上显示在它下面,除非您也修改了它们的位置。如果是这种情况,那么您可以使用 window.getComputedStyle() 计算元素的高度 并且您可以使用该值来设置边距。

var wrapper = document.getElementById("wrapper");
var banner = document.getElementById("banner");
var content = document.getElementById("content");

var bannerHeight = window.getComputedStyle(banner).height;

console.log("Height of the banner is: " + bannerHeight);

content.style.marginTop = bannerHeight;
#wrapper { background: #e0e0e0; }
#banner { background: #ff0; position:fixed; top:0; width:100%; z-index:99; }
#content { background: #66f; position:relative; }
<div id="wrapper">

<div id="banner">
<h1>This is the page banner</h1>
</div>
<div id="content">
<h1>This is FIRST LINE of the main content area of the document.</h1>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
</div>

</div>

关于javascript - 如何将网页向下推以适合顶部栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com