简体   繁体   中英

Unable to update document.body based on scrollY in IE11

I've got the following script on my site, intended to change the body class when the user scrolls more than 20px away from the top of the viewport.

(function ($) {
/// Make nav opaque on scroll
     window.addEventListener('scroll', function () {
      document.body.classList[
         window.scrollY > 20 ? 'add': 'remove'
      ]('scrolled');
     });
})(jQuery);

It works perfectly on Chrome, Safari and Firefox, but not on IE11.

What am I missing?

According to MDN, IE11 does not supportwindow.scrollY . Instead you could use window.pageYOffset , which is an alias for window.scrollY .

As mentioned on MDN,

The pageYOffset property is an alias for the scrollY property:

 window.pageYOffset == window.scrollY; // always true

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example:

 var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

In your case if you intend to support IE 11, you can directly replace scrollY with pageYOffset :

document.body.classList[
     window.pageYOffset > 20 ? 'add': 'remove'
  ]('scrolled');
});

Here's a working fiddle: https://jsfiddle.net/wg3nj06h/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM