开始滚动时已成功添加类名,但滚动时继续添加类。
返回页面顶部后,这些类就被很好地删除了。
function scrollHeader() {
var elmnt = document.getElementById("rbuxApp");
var y = elmnt.scrollTop;
if(y >= 4 && document.getElementById("header").className !== "min-header") {
document.getElementById("header").className += "min-header ";
}
else {
document.getElementById("header").className -= "min-header ";
};
}
最佳答案
document.getElementById("header").className
可以有多个类,在这种情况下,您的条件 document.getElementById("header").className !== "min-header “
不起作用。
您可以按空格分割类,然后查看它是否与任何项目匹配。另外,当您添加另一个类时,您需要在类名前添加一个空格。所以最好尝试这种方式。
//Get the class names in array
var classNames = document.getElementById("header").className.split(/\s+/);
//Check if your class exists already
if(classNames.indexOf('min-header') !== -1) {
//If not add the class to the array
classNames.push('min-header');
//Now join the classes back with space and set it back to the className property
document.getElementById("header").className = classNames.join(" ");
}
当您想通过以下方式从元素中删除类时,可以按照相同的方式进行操作:
var index = classNames.indexOf('min-header');
if(index !== -1) {
classNames.splice(index,1);
document.getElementById("header").className = classNames.join(" ");
}
关于javascript - 为什么这个 JavaScript 函数不断在滚动上添加类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34192875/