[英]I am currently removing jquery from my code and I am not able to convert this Jquery to Javascript
我目前正在从我的网站上删除 Jquery,但我无法成功将其转换为 JavaScript。 我知道它可能非常愚蠢,但我仍然是初学者。 有人可以帮忙吗?
$(document).scroll(function(){
$('.navbar').toggleClass('scrolled', $(this).
scrollTop() > $('.navbar').height());
});
你可以尝试这样的事情:
window.onscroll = function() { var nav = document.querySelector('.navbar'); var isScrolled = document.body.scrollTop > nav.offsetHeight || document.documentElement.scrollTop > nav.offsetHeight; nav.classList.toggle("scrolled", isScrolled); };
.container { height: 2000px; }.nav-link { display: block; color: red; }.scrolled.nav-link { color: blue; }
<div class="container"> <div class="navbar"> Navbar <a class="nav-link">aaa</a> <a class="nav-link">bbb</a> <a class="nav-link">ccc</a> </div> </div>
我们正在订阅窗口的onscroll
事件。 我们使用document.querySelector()
获取对导航栏元素的引用。 然后我们使用该元素高度 ( offsetHeight
) 来确定它是否应该具有.scrolled
class。 最后,我们在导航栏元素的classList
属性上使用了toggle()
方法。
根据评论更新:
如果你必须有许多单独的函数来处理同一个事件,你最好使用window.addEventListener()
语法。
window.addEventListener('scroll', function() { var nav = document.querySelector('.navbar'); var isScrolled = document.body.scrollTop > nav.offsetHeight || document.documentElement.scrollTop > nav.offsetHeight; nav.classList.toggle("scrolled", isScrolled); }); window.addEventListener('scroll', function() { //... console.log('scroll b'); }); window.addEventListener('scroll', function() { //... console.log('scroll c'); });
.container { height: 2000px; }
<div class="container"> <div class="navbar">Navbar</div> </div>
第一行可以用这样的“addEventListener”替换
window.addEventListener('scroll', function (e) {
});
要替换切换 function 您可以使用“classList”属性。 将元素保存在新变量中,然后“element.classList.remove('class')”或“element.classList.add('class')
var navbar = document.getElementById("navbar");
navbar.classList.remove("scrolled");
navbar.classList.add("scrolled");
使用 this.scrollY 获取 window ScrollY position 和 element.clientHeight 获取元素的高度,包括填充(还有其他方法可以获取更适合您需要的高度)
if (this.scrollY > navbar.clientHeight) {}
最终结果将是这样的
window.addEventListener('scroll', function (e) {
var navbar = document.getElementById("navbar");
navbar.classList.remove("scrolled");
if (this.scrollY > navbar.clientHeight) {
navbar.classList.add("scrolled");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.