Willkommen SO,
können Sie mit getBoundingClientRect Methode versuchen. Es gibt Ihnen die Elementposition in Bezug auf das Ansichtsfenster. Schauen Sie sich die Logik des nächsten Codes, es wird Ihnen einen Anhaltspunkt, Ihre Arbeit zu erreichen (Der wichtige Teil ist der erste Code von checkVisibleSection
-Funktion):
HTML-Code
<ul id="navigation">
<li data-section="1"><a class="active" href="#">Section 1</a></li>
<li data-section="2"><a href="#">Section 2</a></li>
<li data-section="3"><a href="#">Section 3</a></li>
<li data-section="4"><a href="#">Section 4</a></li>
<li data-section="5"><a href="#">Section 5</a></li>
</ul>
<section id="section1" class="section" data-section="1">
<header>Section 1</header>
</section>
<section id="section2" class="section" data-section="2">
<header>Section 2</header>
</section>
<section id="section3" class="section" data-section="3">
<header>Section 3</header>
</section>
<section id="section4" class="section" data-section="4">
<header>Section 4</header>
</section>
<section id="section5" class="section" data-section="5">
<header>Section 5</header>
</section>
JavaScript-Code
var nav = document.getElementById("navigation"),
sections = document.querySelectorAll(".section"),
delay = null;
//---Scroll logic
document.addEventListener("scroll", function(){
if(!isNaN(delay)){ clearTimeout(delay); }
delay = setTimeout(checkVisibleSection, 100);
});
//---Check the visible section
function checkVisibleSection(){
var minor = window.innerHeight,
section = null;
//---Select the section closest to the top
[].forEach.call(sections, function(item){
var offset = item.getBoundingClientRect();
if(Math.abs(offset.top) < minor){
minor = Math.abs(offset.top);
section = item;
}
});
//---If the section exists
if(section){
var index = section.dataset.section,
link = nav.querySelector("li[data-section='" + index + "'] a");
//---If the link is not already active
if(!link.classList.contains("active")){
//---Remove the active class
nav.querySelector("a.active").classList.remove("active");
//---Add the active class
link.classList.add("active");
}
}
}
//---Click on buttons
nav.addEventListener("click", function(evt){
evt.preventDefault();
var link = evt.target;
if(link.nodeName.toLowerCase() === "a"){
var section = link.parentNode.dataset.section;
//---Remove the class of the active link
nav.querySelector("a.active").classList.remove("active");
//---Active the link
link.classList.add("active");
//---Scroll to the section
document.getElementById("section" + section).scrollIntoView();
document.body.scrollTop -= 30;
}
});
Hier haben Sie eine JSFiddle mit einem Arbeitsbeispiel.
Mögliche Duplikate von [Wie kann ich erkennen, wenn ein Element in das Ansichtsfenster scrollt] (http://stackoverflow.com/questions/31865815/how-can-i-detect-when-an-element-scrolls-into- das Ansichtsfenster) – vsync