ahooks
Version:
react hooks library
62 lines (61 loc) • 2.54 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _useRafState3 = _interopRequireDefault(require("../useRafState"));
var _useLatest = _interopRequireDefault(require("../useLatest"));
var _domTarget = require("../utils/domTarget");
var _useEffectWithTarget = _interopRequireDefault(require("../utils/useEffectWithTarget"));
function useScroll(target) {
var shouldUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
return true;
};
var _useRafState = (0, _useRafState3["default"])(),
_useRafState2 = (0, _slicedToArray2["default"])(_useRafState, 2),
position = _useRafState2[0],
setPosition = _useRafState2[1];
var shouldUpdateRef = (0, _useLatest["default"])(shouldUpdate);
(0, _useEffectWithTarget["default"])(function () {
var el = (0, _domTarget.getTargetElement)(target, document);
if (!el) {
return;
}
var updatePosition = function updatePosition() {
var newPosition;
if (el === document) {
if (document.scrollingElement) {
newPosition = {
left: document.scrollingElement.scrollLeft,
top: document.scrollingElement.scrollTop
};
} else {
// When in quirks mode, the scrollingElement attribute returns the HTML body element if it exists and is potentially scrollable, otherwise it returns null.
// https://developer.mozilla.org/zh-CN/docs/Web/API/Document/scrollingElement
// https://stackoverflow.com/questions/28633221/document-body-scrolltop-firefox-returns-0-only-js
newPosition = {
left: Math.max(window.pageXOffset, document.documentElement.scrollLeft, document.body.scrollLeft),
top: Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
};
}
} else {
newPosition = {
left: el.scrollLeft,
top: el.scrollTop
};
}
if (shouldUpdateRef.current(newPosition)) {
setPosition(newPosition);
}
};
updatePosition();
el.addEventListener('scroll', updatePosition);
return function () {
el.removeEventListener('scroll', updatePosition);
};
}, [], target);
return position;
}
var _default = exports["default"] = useScroll;