Search
<script>
let ele = document.querySelector(".notion-page-content");
let headers = ele.querySelectorAll("h2, h3, h4");
let content = document.querySelector(".notion-table_of_contents-block > div");
let currentActiveIndex = -1; // 현재 활성화된 헤더의 인덱스를 추적
let callback = (entries, observer) => {
if (!headers && !content) return;
let foundNewActive = false; // 새로운 활성화된 헤더를 찾았는지 여부
headers.forEach((header, index) => {
let headerPosition = header.getBoundingClientRect();
if (headerPosition.top <= 300 && headerPosition.bottom > 0) {
// 새로운 헤더가 뷰포트 상단 300px 이내에 들어왔을 때
if (currentActiveIndex !== index) {
foundNewActive = true;
currentActiveIndex = index;
}
}
});
if (foundNewActive) {
// 새로운 활성화된 헤더가 있을 경우, 모든 색상을 초기화하고 새 헤더의 색상을 업데이트
content.childNodes.forEach((node, idx) => {
node.style.color = idx === currentActiveIndex ? "red" : "";
});
}
};
let observer = new IntersectionObserver(callback, {
rootMargin: "-300px 0px 0px 0px",
threshold: [0, 1]
});
headers.forEach(header => {
observer.observe(header);
});
</script>
JavaScript
복사