我正在尝试使用 JS 动态调整标题的粘性定位。我怎样才能实现这个目标?

问题描述 投票:0回答:1

这是我的第一个个人项目,我在使用 JS 动态更改标题上的粘性定位时遇到困难。我想做的就是在滚动到介绍类的底部后删除我在头类上设置的粘性定位。如何使用 JavaScript 实现此目的?

这是我的标题和简介部分的 html 代码。

<header id="head">
        <div class="title">
            <h1 style="font-size: 2.5rem; margin-left: 10px;">
                Health & Wellness
            </h1>
            <img src="C:\Tech Stack\Website Design\CSS Practicee\Images\download (2).png" style="height: 60px; width: 100px; border: none; object-fit: cover;">
        </div>
        <nav class="navigation">
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarNav"></div>
            <button type="button" class="btn btn-light" id="search"><i class="bi bi-search" style="font-size: 15px;"></i>Search</button>
            <button class="btn btn-primary" id="home">Home</button>
            <button class="btn btn-success" id="about">About</button>
            <button class="btn btn-info" id="services" style="color: white">Services</button>
        </div>
        </nav>
    </header>

    <div class="intro" id="intro">
        <h2>Health & Wellness Blog Articles</h2>
        <p>Read posts from experts at Harvard Health Publishing covering a variety of health topics and perspectives on medical news.
        </p>
    </div>

这是CSS

#head{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px;
    background-color: #CDFFFC;
    min-height: 150px;
    padding: 15px;
    
}
.sticky {
    position: sticky;
    top: 0;
    width: 100%;
    z-index: 1000;
    background-color: #CDFFFC;

这是 Javascript



window.addEventListener('scroll', function() {
    
    const header = document.getElementById('head');
    const introSection = document.getElementById ('intro');

    // Calculate the bottom position of the intro section

    const introBottom = introSection.offsetTop + introSection.offsetHeight;

    if(window.scrollY >= introBottom) {
        header.classList.remove('sticky');
    }else {
        header.classList.add('sticky');
    }
});
javascript css dynamic positioning sticky
1个回答
0
投票

只需将标题和简介包装到同一个容器中即可。粘性元素将始终保留其容器的子元素。因此,一旦父元素离开它,它就会离开屏幕。

无需JS:

header {
  position: sticky;
  top: 0;
  background-color: blue;
  color: white;
  z-index: 10;
}


main {
  min-height: 500vh;
}
<div>
  <header>Header</header>
  <div id="intro">
    <p>Intro</p>
    <p>Intro</p>
    <p>Intro</p>
  </div>
</div>
<main>
  <p>Further Content</p>
</main>

© www.soinside.com 2019 - 2024. All rights reserved.