Why is body.scrollTop deprecated?

后端 未结 4 1480
日久生厌
日久生厌 2020-12-01 08:50

It seems body.scrollTop (and body.scrollLeft) are deprecated in ES5 strict-mode. What is the reason for this, given that it still seems okay to use

相关标签:
4条回答
  • 2020-12-01 09:29

    The following code works for me to set the popup in a correct position whenever the click event fires, for all browsers.

    var scrollTop = window.scrollY; //For all browsers.
    var scrollTop = document.body.scrollTop; //This works for only IE Edge specific versions
    
    0 讨论(0)
  • 2020-12-01 09:36

    I noticed my code stop working on newer versions of Chrome. I fixed it by using window.scrollY

    Before:

    var scrollTop = document.body.scrollTop;
    

    Now:

    var scrollTop = window.scrollY;
    

    It works all the time now. You can find more documentation here.

    Also, I was using:

    document.body.scrollTop = 0;
    

    now I replaced it with:

    window.scrollTo(0, 0);
    
    0 讨论(0)
  • 2020-12-01 09:40

    scrollTop refers to how much the element is scrolled. This means body shouldn't have a scrollTop because it is never scrolled, body has the topmost scrollbar so it's contents can be scrolled but not body itself.
    The last picture on this page explains a lot:
    https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

    0 讨论(0)
  • 2020-12-01 09:42

    It's Chrome's own incorrect behavior that is deprecated, and they're warning authors to stop relying on it.

    The scrolling viewport is represented by document.documentElement (<html>) in standards mode or <body> in quirks mode. (Quirks mode emulates the document rendering of Navigator 4 and Explorer 5.)

    Chrome uses body.scrollTop to represent the viewport's scroll position in both modes, which is wrong. It sounds like they want to fix this so they're encouraging authors to script for the standard behavior.

    I don't think you need to change your code. There's nothing wrong with using body.scrollTop in standards mode so long as you understand it represents the scroll position of body only (typically 0, unless you've given body a scroll box).

    You can see the warning by executing document.body.scrollTop in the console:

    body.scrollTop is deprecated in strict mode. Please use documentElement.scrollTop if in strict mode and body.scrollTop only if in quirks mode.

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