我的 js 代码在 IE10 上不起作用

My js code won't work on IE10

本文关键字:不起作用 IE10 js 代码 我的      更新时间:2023-09-26

这是我的JS代码。

 <script>
var sticky = document.querySelector('.sticky');
var origOffsetY = sticky.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? sticky.classList.add('fixed') :
                              sticky.classList.remove('fixed');
}
document.addEventListener('scroll', onScroll);
</script> 

它用于让div 保持原位,即使用户向下滚动也是如此。

它在IE10中不起作用(IE10有querySelectorclassListaddEventListener,所以不是那样)。

IE10不支持scrollY。您必须在document.documentElement上使用scrollTop

var sticky = document.querySelector('.sticky');
var origOffsetY = sticky.offsetTop;
var hasScrollY = 'scrollY' in window;
function onScroll(e) {
  var y = hasScrollY ? window.scrollY : document.documentElement.scrollTop;
  y >= origOffsetY ? sticky.classList.add('fixed') : sticky.classList.remove('fixed');
}
document.addEventListener('scroll', onScroll);

现场示例 |实时源码

(您可能不需要检查,可能所有目标浏览器都支持document.documentElement.scrollTop,您可以始终使用它。