[英]How can I change the background colour of my menu when i scroll down?
I'm a pure student's beginner, right now I'm trying to create an adaptive menu for my project, but I need to change the color of my background because white on white is a little bit problematic.我是一个纯学生的初学者,现在我正在尝试为我的项目创建一个自适应菜单,但我需要更改背景颜色,因为白底白字有点问题。
What I tried is to create a script in order to add a class 'scroll' to my 'nav' when I'm scrolling down, and removed it when I'm going back to the top.我尝试创建一个脚本,以便在我向下滚动时将 class '滚动'添加到我的'导航',并在我返回顶部时将其删除。
But as I said I'm a beginner, and it seems I did something wrong with either my script or my CSS.但正如我所说,我是一个初学者,似乎我的脚本或 CSS 有问题。
Can you help me to understand how where I did something wrong?你能帮我理解我在哪里做错了吗?
Thanks for the help !谢谢您的帮助 !
PS: Sorry for my english I did my best. PS:对不起我的英语我尽力了。
`https://codepen.io/Raz7/pen/zYKoJzY`
it's completly messed up, probably due to all the image I put in.它完全搞砸了,可能是由于我输入的所有图像。
In your script tag you are using a JQuery Selector "$" but you did not add the JQuery library.在您的脚本标签中,您使用的是 JQuery 选择器“$”,但您没有添加 JQuery 库。
To keep things simple I will use the built-in querySelector from the document object and Vanilla Javascript.为了简单起见,我将使用文档 object 和 Vanilla Javascript 中的内置 querySelector。
The following code will do what you want:以下代码将执行您想要的操作:
let timeout;
window.addEventListener('scroll', function (e) {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup the new requestAnimationFrame()
timeout = window.requestAnimationFrame(function () {
// Run our scroll functions
let nav = document.querySelector('nav');
if (document.querySelector('header').getBoundingClientRect().top !== 0) {
nav.classList.add('scroll');
} else {
nav.classList.remove('scroll');
}
});
}, false);
To actually know what the distance to the top is you need a point of reference, in this script I used the header element as a point of reference since the header is relative to the body tag.要真正知道到顶部的距离是多少,您需要一个参考点,在此脚本中,我使用 header 元素作为参考点,因为 header 是相对于主体标签的。 If the header distance to top is not 0 then add the scroll class to the nav element else remove it.
如果 header 到顶部的距离不为 0,则将滚动 class 添加到导航元素,否则将其删除。 You can see also a timeout and requestAnimationFrame, this helps de-bouncing the scroll event.
您还可以看到超时和 requestAnimationFrame,这有助于消除滚动事件的反弹。
Instead of using the JQuery Library, if you are a beginner I suggest learning about Vanilla Javascript and the DOM.不要使用 JQuery 库,如果您是初学者,我建议您了解 Vanilla Javascript 和 DOM。
https://www.w3schools.com/js/js_htmldom.asp https://www.w3schools.com/js/js_htmldom.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.