我想知道如何使用HTML,CSS和JS编写粘性navbar
。我没有使用jQuery创建了粘性导航,但是height
函数无法正常工作。有人可以建议我如何调用此height
函数吗?如何在纯JavaScript中找到height
?
document.addEventListener("DOMContentLoaded", function() {
'use strict';
var c, currentScrollTop = 0;
var navbar = document.querySelector(".nav");
window.addEventListener('scroll', function() {
var a = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var b = navbar.hight();
currentScrollTop = a;
if (c < currentScrollTop && a > b + b) {
navbar.addClass("scrollUp");
} else if (c > currentScrollTop && !(a <= b)) {
navbar.removeClass("scrollUp");
}
c = currentScrollTop;
});
});
<nav>
<div class="container">
<a href="#" id="brand">Brand</a>
<button>
<span></span>
<span></span>
<span></span>
</button>
<ul class="navbar-menu">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Team</a>
</li>
<li>
<a href="#">Timeline</a>
</li>
<li>
<a href="#">Conact</a>
</li>
</ul>
</div>
</nav>
答案 0 :(得分:2)
nav
不是课程。这是一个HTML标记。因此,document.querySelector(".nav")
将返回一个空节点列表。
更改
document.querySelector(".nav")
var b = navbar.height();
至
document.querySelector("nav")
var b = navbar.clientHeight;
// or
var height = navbar.offsetHeight;
document.addEventListener("DOMContentLoaded", function() {
'use strict';
var c, currentScrollTop = 0;
var navbar = document.querySelector("nav");
window.addEventListener('scroll', function() {
var a = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var b = navbar.clientHeight
currentScrollTop = a;
if (c < currentScrollTop && a > b + b) {
navbar.addClass("scrollUp");
} else if (c > currentScrollTop && !(a <= b)) {
navbar.removeClass("scrollUp");
}
c = currentScrollTop;
});
});
<nav>
<div class="container">
<a href="#" id="brand">Brand</a>
<button>
<span></span>
<span></span>
<span></span>
</button>
<ul class="navbar-menu">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Team</a>
</li>
<li>
<a href="#">Timeline</a>
</li>
<li>
<a href="#">Conact</a>
</li>
</ul>
</div>
</nav>