[英]classList.add() is not working in JavaScript
I tried to stick the social share bar of my website on scroll according to the tutorial here . 我试图按照此处的教程将我的网站的社交分享栏滚动显示。
Link to my website: https://www.staging5.howtostudycantonese.com/how-to-say-crazy-in-cantonese/ 链接到我的网站: https : //www.staging5.howtostudycantonese.com/how-to-say-crazy-in-cantonese/
I made some modification to the code, and somehow it doesn't work. 我对代码进行了一些修改,但不知何故。 I have tested everything with the inspector and I found out the class of the element of social share bar does not change when I scrolled past it.
我已经用检查员测试了所有内容,发现滚动到上方时,社交共享栏元素的类别没有改变。 I believe
classList.add
is the problem there. 我相信
classList.add
是那里的问题。 I am not sure why it is not working. 我不确定为什么它不起作用。
The code I am using: 我正在使用的代码:
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");
}
}
You are setting the variables before the elements are loaded, that's why they are null. 您要在元素加载之前设置变量,这就是为什么它们为null的原因。
use onload function to avoid this: 使用onload函数可以避免这种情况:
var header;
var sticky;
window.onload = function () {
header = document.querySelector("div.wp-socializer.wpsr-buttons.wpsr-row-1");
sticky = header.offsetTop;
}
You have to below lines in myFunction 您必须在myFunction中的以下行
var header = document.querySelector("div.wp-socializer.wpsr-buttons.wpsr-row-1");
var sticky = header.offsetTop;
like 喜欢
function myFunction() {
var header = document.querySelector("div.wp-socializer.wpsr-buttons.wpsr-row-1");
var sticky = header.offsetTop;
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.