繁体   English   中英

为什么此JavaScript函数不断在滚动上添加className?

[英]Why does this JavaScript function continually add the className on scroll?

开始滚动时已成功添加类名,但滚动时仍继续添加类。

返回页面顶部后,就可以删除这些类。

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(" ");
}

因为您要使用+=附加到现有的类名

document.getElementById("header").className += "min-header ";

更改为

document.getElementById("header").className = "min-header " ;

答案就在添加类名称的行:

document.getElementById("header").className += "min-header ";

您在末尾添加“ min-header”,但仅将其与没有空格的“ min-header”进行比较。 因此,您元素的className绝不会等于“ min-header”且没有空格,因此一遍又一遍地添加了该类。 一种更强大的方法是在元素中利用classList对象。 这里是一些文档: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

您可以使用element.classList.add()的类添加到您的元素, element.classList.contains()检查,如果它已经在那里, element.classList.remove()把它关闭的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM