[英]make two similar javascript functions work together
I started with Javascript recently. 我最近开始使用Javascript。 I found a piece of code which changes the class of an object on scroll using pure javascript.
我发现了一段代码,可以使用纯JavaScript更改滚动对象的类。 Here is that code -
这是代码-
window.onscroll = function() {
if (window.scrollY > 1) {
document.getElementById('nav2').className = "after";
} else {
document.getElementById('nav2').className = "before";
}};
window.onscroll = function() {
if (window.scrollY > 1) {
document.getElementById('list').className = "ul2";
} else {
document.getElementById('list').className = "ul";
}};
The problem is that in this code only the second function runs , the first one does not run until i remove the second function. 问题是在这段代码中,只有第二个函数运行,第一个函数直到我删除第二个函数才运行。 Please suggest any pure javascript method to solve this issue
请提出任何纯JavaScript方法来解决此问题
Problem is because when you are saying second time window.onscroll=somefun
it's overwriting the existing one. 问题是因为当您说第二次
window.onscroll=somefun
它正在覆盖现有window.onscroll=somefun
。 So now only it will call the second function onscroll
. 所以现在只有它会调用第二个函数
onscroll
。
Just write every thing in one function like bellow 只需将以下所有内容写在一个函数中即可
window.onscroll = function() {
if (window.scrollY > 1) {
document.getElementById('nav2').className = "after";
document.getElementById('list').className = "ul2";
} else {
document.getElementById('nav2').className = "before";
document.getElementById('list').className = "ul";
}};
If you assign it like this ( window.onscroll = ...
) then you can only ever have one function in there (the next would overwrite the first). 如果这样分配它(
window.onscroll = ...
),则只能在其中拥有一个功能(下一个将覆盖第一个功能)。
The better way would be to add an event listener . 更好的方法是添加一个事件监听器 。
in your case that might be 在你的情况下可能是
window.addEventListener('scroll', function (event) {
//...
}, true);
window.onscroll = function() {
if (window.scrollY > 1) {
document.getElementById('nav2').className = "after";
document.getElementById('list').className = "ul2";
} else {
document.getElementById('nav2').className = "before";
document.getElementById('list').className = "ul";
}};
U can use code like this.. U可以使用这样的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.