Using Doctype let scrollTop return 0, why?

后端 未结 1 1743
灰色年华
灰色年华 2021-01-16 07:48

When I put this Doctype in my documents document.body.scrollTop returns zero.



        
相关标签:
1条回答
  • 2021-01-16 08:16

    When you use that Doctype, you'll put every current browser in the so-called Almost Standards mode, without it you'll be in Quirks Mode.

    As you can read on this page,

    [m]ost browsers provide window.pageXOffset/pageYOffset. These are completely reliable. Once again, Internet Explorer is the odd one out, as it does not provide these properties. Internet Explorer and some other browsers will provide document.body.scrollLeft/Top. In strict mode, IE 6 and a few other browsers, provide document.documentElement.scrollLeft/Top.

    A script provided there calculates the value you want:

    function getScrollXY() {
      var scrOfX = 0, scrOfY = 0;
      if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
      } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
      } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
      }
      return [ scrOfX, scrOfY ];
    }
    

    Another interesting article appeared on QuirksMode, A tale of two viewports.

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