[英]Javascript vertical scrolling function
我正在尝试使用JavaScript检测页面上的滚动。 这样,当用户滚动了一定数量的页面时,我可以更改某些元素的类和属性。 这是我的JS函数:
function detectScroll() {
var header = document.querySelector(".headerOrig"),
header_height = getComputedStyle(header).height.split('px')[0],
fix_class = "changeColor";
if( window.pageYOffset > header_height ) {
header.classList.add(fix_class);
}
if( window.pageYOffset < header_height ) {
header.classList.remove(fix_class);
}
var change = window.setInterval(detectScroll, 5000);
}
我在页面加载时调用它:
<body onload="detectScroll();">
但是,我有这个问题-我需要设置一个很小的间隔,以便调用函数并立即更改类。 但是然后页面冻结,除了JS函数之外的所有东西都运行非常缓慢。 有没有更好的方法可以在JavaScript中实现呢?
感谢您的任何建议/建议。
您将要更改几件事。 首先,我们可以使用onscroll而不是间隔。 但是,您还需要尽可能多地缓存,以减少滚动条上的计算量。 更进一步,您应该使用requestAnimationFrame (或者对于较旧的浏览器,通常只是简单地使用“ debounce”-请参阅链接)。 这样可以确保您的工作仅在浏览器计划重新粉刷时发生。 例如,当用户滚动时,实际的滚动事件可能会触发数十次,但页面仅重新绘制一次。 您只关心该一次重绘,并且如果我们可以避免在其他X次上进行工作,它将更加顺畅:
// Get our header and its height and store them once
// (This assumes height is not changing with the class change).
var header = document.querySelector(".headerOrig");
var header_height = getComputedStyle(header).height.split('px')[0];
var fix_class = "changeColor";
// This is a simple boolean we will use to determine if we are
// waiting to check or not (in between animation frames).
var waitingtoCheck = false;
function checkHeaderHeight() {
if (window.pageYOffset > header_height) {
header.classList.add(fix_class);
}
if (window.pageYOffset < header_height) {
header.classList.remove(fix_class);
}
// Set waitingtoCheck to false so we will request again
// on the next scroll event.
waitingtoCheck = false;
}
function onWindowScroll() {
// If we aren't currently waiting to check on the next
// animation frame, then let's request it.
if (waitingtoCheck === false) {
waitingtoCheck = true;
window.requestAnimationFrame(checkHeaderHeight);
}
}
// Add the window scroll listener
window.addEventListener("scroll", onWindowScroll);
使用onscroll
而不是onload
因此您无需间隔调用该函数。 如果您使用onscroll
则当有任何滚动应用程序出现时,您的dedectScroll
函数将自动触发
<body onscroll="detectScroll();">
您的函数正在递归添加一个间隔,您应该通过以下方式向滚动事件添加一个事件侦听器:
function detectScroll() {
var header = document.querySelector(".headerOrig"),
header_height = getComputedStyle(header).height.split('px')[0],
fix_class = "changeColor";
if( window.pageYOffset > header_height ) {
header.classList.add(fix_class);
}
if( window.pageYOffset < header_height ) {
header.classList.remove(fix_class);
}
}
window.addEventListener("scroll",detectScroll);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.