监视导航功能:逻辑判断
编写一个简单的监视导航功能。
<!-- =panel: start -->
<div class="panel" role="region"></div>
<!-- =panel: end -->
<script>
var em = document.querySelectorAll(".panel");
var viewHeight = window.innerHeight;
var clientHeight = document.body.clientHeight;
var timeOut = null;
em.forEach(function (em, index) {
watchNav(em);
});
function watchNav(em) {
var emHeight = em.offsetHeight;
var emTop = em.offsetTop;
clearTimeout(timeOut);
window.addEventListener("scroll", function (e) {
var scrollY = window.scrollY;
timeOut = setTimeout(function () {
// Logical judgment: how to optimize, want better implementation.
// Such as reducing the if statement
// ++++++++++++++++
if (scrollY > emTop || scrollY + viewHeight / 2 > emTop || scrollY + viewHeight > emTop + emHeight) {
console.log("...activing...");
em.classList.add("view-focus");
}
else {
console.log("none");
em.classList.remove("view-focus");
}
if (scrollY > emTop + emHeight / 2) {
console.log("none");
em.classList.remove("view-focus");
}
// ++++++++++++++++
}, 40);
}, false);
}
</script>