IE8 alternative to window.scrollY?

前端 未结 8 866
一向
一向 2020-11-29 06:02

I\'m trying to determine how many pixels down I\'ve scrolled using window.scrollY. But this isn\'t supported in IE8. What is the safe, cross-browser alternative

相关标签:
8条回答
  • window.scrollY & window.scrollX works fine in all modern browers like (Chrome, FireFox & Safari) but does not work in IE so to fix the use window.pageXOffset or window.pageYOffset.

    Here is a sample code I wrote to fix ie issue so that the programmatic scrolling works in all browsers including IE

    if((window.scrollY || window.pageYOffset) >= 1100){
       //alert('Switch to land');
        $('#landTrst').trigger('click'); // your action goes here
    }else if ((window.scrollY || window.pageYOffset) <= 900) {   
        //alert('Switch to Refernce Letter');
         $('#resLet').trigger('click'); // your action goes here
    }                            
    
    0 讨论(0)
  • 2020-11-29 06:32

    Based on Mozilla, and answers above, I have a created the functions below to more easily get the coords:

    var windowEl = (function () {
        var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
        function scroll() {
            return { left: scrollLeft, top: scrollTop };
        };
        function scrollLeft() {
            return window.scrollX || window.pageXOffset || (isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft);
        };
        function scrollTop() {
            return window.scrollY || window.pageYOffset || (isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop);
        };
        return {
            scroll: scroll,
            scrollLeft: scrollLeft,
            scrollTop: scrollTop
        }
    })();
    

    According to the Mozilla documentation, as cited by lifetimes above, the The pageXOffset property is an alias for the scrollX property, so is stictly speaking not necessary.

    Anyhoo, usage is:

    var scroll = windowEl.scroll();
    // use scroll.left for the left scroll offset
    // use scroll.top for the top scroll offset
    
    var scrollLeft = windowEl.scrollLeft();
    // the left scroll offset
    
    var scrollTop = windowEl.scrollTop();
    // the top scroll offset
    

    Tested & works on Chrome, Firefox, Opera, Edge (8-Edge), IE (7-11), IE8 on XP

    0 讨论(0)
提交回复
热议问题