我有两个window.onscroll
函数,每个函数都起作用,但是当它们都被添加时,只有最先列出的一个函数才起作用。如何结合这两个功能?
一个功能滚动了我表的标题,而另一个功能实现了返回顶部功能。
<script>
const myEventHandlers = {
toggleSticky: function() {
let header = document.getElementById("ipfixedheader");
let sticky = header.offsetTop;
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
},
toggleButton: function() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
},
scrollToTop: function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
}
window.addEventListener("scroll", function(e) {
myEventHandlers.toggleSticky();
});
</script>
粘滞功能有效,滚动到顶部按钮有效,但是单击时不起作用。
答案 0 :(得分:1)
这个注释太长了,因此这里是一个将2个事件附加到文档的滚动事件的示例。基本上,只需调用window.addEventListener("scroll" ...
两次即可添加您的处理程序。
window.addEventListener("scroll", function(e){
console.log('First Event Handler');
});
window.addEventListener("scroll", function(e){
console.log('Second Event Handler');
});
div{
height: 5em;
}
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
<div>
asdasd
</div>
编辑 这是一个基于您问题中更新代码的示例。我已经在代码中添加了注释,以便为您解释。
// Let's declare all the functions you want to execute in your event listners so they are all in 1 place
const myEventHandlers = {
toggleSticky: function() {
// find the header and get the offset
let header = document.getElementById("ipfixedheader");
let sticky = header.offsetTop;
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
},
toggleButton: function() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
},
scrollToTop: function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
}
// Now let's add a new event listner for each of the function you want to call
window.addEventListener("scroll", function(e) {
myEventHandlers.toggleSticky();
});
window.addEventListener("scroll", function(e) {
myEventHandlers.toggleButton();
});
// As you can quickly see you don't actually need 2 event handlers because you could simply add your call to myEventHandlers.toggleButton inside the first event listener.
// Also you never actually called your scrollToTop function, so you need to add that call where it makes sense.