<!-- ヘッダー -->
<header class="header" id="header">
<div class="header-content">
<div class="header-logo">Logo</div>
<nav class="header-nav">
<a href="#" class="nav-link">Home</a>
<a href="#" class="nav-link">About</a>
<a href="#" class="nav-link">Contact</a>
</nav>
</div>
</header>
<!-- センチネル要素 -->
<div id="sentinel" style="height: 1px;"></div>
<!-- メインコンテンツ -->
<main class="main">
<div class="card">
<h2>コンテンツセクション1</h2>
<p>スクロールしてヘッダーの動作を確認してください。</p>
</div>
<div class="card">コンテンツカード2</div>
<div class="card">コンテンツカード3</div>
<div class="card">コンテンツカード4</div>
</main>
<div id="status" class="status"></div>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 200vh;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 60px;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
z-index: 1000;
}
.header--hidden {
transform: translateY(-100%);
}
.header-content {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.header-logo {
font-size: 1.5rem;
font-weight: bold;
}
.header-nav {
display: flex;
gap: 20px;
}
.nav-link {
color: #333;
text-decoration: none;
}
.main {
max-width: 1200px;
margin: 60px auto 0;
padding: 20px;
}
.card {
background: #f5f5f5;
padding: 20px;
margin-bottom: 20px;
border-radius: 8px;
height: 320px;
}
.status {
position: fixed;
bottom: 20px;
right: 20px;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px 20px;
border-radius: 5px;
font-size: 0.9rem;
z-index: 1001;
display: none; /* 初期状態では非表示 */
}
View Compiled
const header = document.getElementById("header");
const sentinel = document.getElementById("sentinel");
const status = document.getElementById("status");
// Intersection Observerのコールバック関数
const observerCallback = (entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
// ヘッダーを表示
header.classList.remove("header--hidden");
updateStatus("Header Shown");
} else {
// ヘッダーを非表示
header.classList.add("header--hidden");
updateStatus("Header Hidden");
}
}
};
// 状態を更新する関数
const updateStatus = (message) => {
status.textContent = message;
status.style.display = "block";
// 数秒後に非表示にする(オプション)
setTimeout(() => {
status.style.display = "none";
}, 3000); // 2秒後に非表示
};
// Intersection Observerのオプション
const observerOptions = {
root: null,
threshold: 0
};
// Intersection Observerの作成と監視開始
const observer = new IntersectionObserver(observerCallback, observerOptions);
observer.observe(sentinel);
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.