<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Anchor Adjustment</title>
<style>
body {
margin: 0;
}
header {
position: fixed;
top: 0;
width: 100%;
height: 60px; /* ヘッダーの高さ */
background: #333;
color: white;
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
main {
padding-top: 60px; /* ヘッダー高さ分の余白 */
}
section {
padding: 20px;
margin: 50px 0;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<header>Fixed Header</header>
<main>
<nav>
<a href="./jsscrollpadding.html#section1">Go to Section 1</a> |
<a href="#section2">Go to Section 2</a> |
<a href="./jsscrollpadding.html#section3">Go to Section 3</a>
</nav>
<section id="section1">
<h2>Section 1</h2>
<p>Content for Section 1</p>
</section>
<section id="section2">
<h2>Section 2</h2>
<p>Content for Section 2</p>
</section>
<section id="section3">
<h2>Section 3</h2>
<p>Content for Section 3</p>
</section>
</main>
<script>
document.addEventListener("DOMContentLoaded", () => {
// ヘッダーの要素を取得
const header = document.querySelector("header");
// ヘッダーの高さを取得
const getHeaderHeight = () => (header ? header.offsetHeight : 0);
// アンカーリンクのスクロール位置を調整
const scrollToAnchor = (hash) => {
if (hash) {
const targetElement = document.querySelector(hash);
if (targetElement) {
const offset = getHeaderHeight(); // ヘッダーの高さ分をずらす
const topPosition =
targetElement.getBoundingClientRect().top +
window.pageYOffset -
offset;
window.scrollTo({ top: topPosition, behavior: "smooth" });
}
}
};
// ページロード時のURLにアンカーがある場合
if (location.hash) {
scrollToAnchor(location.hash);
}
// アンカーリンククリック時のスクロール制御
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
anchor.addEventListener("click", (event) => {
event.preventDefault(); // デフォルト動作をキャンセル
const targetId = anchor.getAttribute("href");
scrollToAnchor(targetId); // スクロール位置を調整
});
});
});
</script>
</body>
</html>
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme