可以帮助我使用这段代码吗?不知道为什么它不起作用......
function init() {
window.addEventListener('scroll', function(e) {
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 10,
header = document.querySelector("header");
if(distanceY > shrinkOn) {
classie.add(header, "is-not-top");
classie.remove(header, "is-top");
} else {
if(classie.has(header, "is-not-top")) {
classie.remove(header, "is-not-top");
classie.add(header, "is-top");
}
}
});
}
window.onload = init();
这应该将类is-not-top添加到标题类中,但它不会这样做...什么错了? thx:D
编辑: 将代码更改为:
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 10,
header = document.getElementById("header");
if (distanceY > shrinkOn) {
header.classList.add("is-not-top");
header.classList.remove("is-top");
} else {
if (header.classList.has("is-not-top")) {
header.classList.remove("is-not-top");
header.classList.add("is-top");
}
}
});
}
window.onload = init;
答案 0 :(得分:0)
首先,在设置回调时,请name
引用,而不是name()
,如window.onload = init
。
header = document.querySelector("header");
两件事:首先,querySelector
选择一个元素。 querySelectorAll
选择所有匹配的元素,如JQuery。其次,word
自己搜索<word>
元素。如果您想查找<div class="word">
元素,请查询.word
。
所以,新行看起来像这样。
header = document.querySelectorAll(".header");
我假设classie
可以在NodeLists上运行,因为我之前没有使用它。