document.body.scrollTop Firefox returns 0 : ONLY JS

前端 未结 3 1298
清酒与你
清酒与你 2020-11-27 04:36

Any alternatives in pure javascript?

The following works in opera, chrome and safari. Have not tested yet on explorer:

http://monkey-me.herokuapp.com

3条回答
  •  醉梦人生
    2020-11-27 05:05

    Instead of using IF conditions, there's easier way to get proper result by using something like this logical expression.

    var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    

    Both parts return zero by default so when your scroll is at zero position this will return zero as expected.

    bodyScrollTop = 0 || 0 = 0
    

    On page-scroll one of those parts will return zero and another will return some number greater than zero. Zeroed value evaluates to false and then logical OR || will take another value as result (ex. your expected scrollTop is 300).

    Firefox-like browsers will see this expression as

    bodyScrollTop = 300 || 0 = 300
    

    and rest of browsers see

    bodyScrollTop = 0 || 300 = 300
    

    which again gives same and correct result.

    In fact, it's all about something || nothing = something :)

提交回复
热议问题