Window 滚动事件在 Microsoft Edge 中不起作用
Window Scroll event doesn't work in Microsoft Edge
我已经设置了一个简单的功能来添加 class 到 header 当从文档顶部滚动一定数量的像素时,它在任何地方都有效,但在 Edge 中无效。知道这是为什么吗?
控制台中没有错误,什么都没有,只是不起作用。
const headerScrollClass = () => {
window.addEventListener('scroll', throttle(callback, 100));
}
function throttle(fn, wait) {
let time = Date.now();
return function () {
if ((time + wait - Date.now()) < 0) {
fn();
time = Date.now();
}
}
}
const callback = () => {
if (document.documentElement.scrollTop > 100) {
document.querySelector('.header').classList.add('header--top');
} else {
document.querySelector('.header').classList.remove('header--top');
}
}
正如Huangism所说,document.documentElement.scrollTop
Microsoft Edge似乎不支持。您可以在 w3schools 中尝试 the example。你会发现,如果你只使用document.documentElement
,它在Edge中是行不通的。所以我认为你应该在 Edge 中使用 document.body.scrollTop
。
参考:https://www.w3schools.com/jsref/prop_element_scrolltop.asp
您可以尝试以下代码使其在不同的浏览器中兼容:
var scrollTop = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
我已经设置了一个简单的功能来添加 class 到 header 当从文档顶部滚动一定数量的像素时,它在任何地方都有效,但在 Edge 中无效。知道这是为什么吗?
控制台中没有错误,什么都没有,只是不起作用。
const headerScrollClass = () => {
window.addEventListener('scroll', throttle(callback, 100));
}
function throttle(fn, wait) {
let time = Date.now();
return function () {
if ((time + wait - Date.now()) < 0) {
fn();
time = Date.now();
}
}
}
const callback = () => {
if (document.documentElement.scrollTop > 100) {
document.querySelector('.header').classList.add('header--top');
} else {
document.querySelector('.header').classList.remove('header--top');
}
}
正如Huangism所说,document.documentElement.scrollTop
Microsoft Edge似乎不支持。您可以在 w3schools 中尝试 the example。你会发现,如果你只使用document.documentElement
,它在Edge中是行不通的。所以我认为你应该在 Edge 中使用 document.body.scrollTop
。
参考:https://www.w3schools.com/jsref/prop_element_scrolltop.asp
您可以尝试以下代码使其在不同的浏览器中兼容:
var scrollTop = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;