我尝试根据教程here将我网站的社交分享栏粘在滚动条上.
链接到我的网站:https://www.staging5.howtostudycantonese.com/how-to-say-crazy-in-cantonese/
我对代码做了一些修改,但不知何故它不起作用。我已经用检查员测试了所有内容,发现当我滚动过去时,社交共享栏元素的类不会改变。我相信 classList.add
就是那里的问题。我不确定为什么它不起作用。
我正在使用的代码:
window.onscroll = function() {myFunction()};
var header = document.querySelector("div.wp-socializer.wpsr-buttons.wpsr-row-1");
var sticky = header.offsetTop;
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
最佳答案
您在加载元素之前设置变量,这就是它们为空的原因。
使用 onload 函数来避免这种情况:
var header;
var sticky;
window.onload = function () {
header = document.querySelector("div.wp-socializer.wpsr-buttons.wpsr-row-1");
sticky = header.offsetTop;
}
关于javascript - classList.add() 在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57478292/