vue-hooks-plus
Version:
Vue hooks library
59 lines (58 loc) • 1.63 kB
JavaScript
import { ref, readonly } from "vue";
import { getTargetElement } from "../utils/domTarget";
import useEffectWithTarget from "../utils/useEffectWithTarget";
function useScroll(target, shouldUpdate = () => true) {
const position = ref();
const shouldUpdateRef = ref(shouldUpdate);
useEffectWithTarget(
() => {
const el = getTargetElement(target, document);
if (!el) {
return;
}
const updatePosition = () => {
let newPosition;
if (el === document) {
if (document.scrollingElement) {
newPosition = {
left: document.scrollingElement.scrollLeft,
top: document.scrollingElement.scrollTop
};
} else {
newPosition = {
left: Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
),
top: Math.max(
window.pageXOffset,
document.documentElement.scrollLeft,
document.body.scrollLeft
)
};
}
} else {
newPosition = {
left: el.scrollLeft,
top: el.scrollTop
};
}
if (shouldUpdateRef.value(newPosition)) {
position.value = newPosition;
}
};
updatePosition();
el.addEventListener("scroll", updatePosition);
return () => {
el.removeEventListener("scroll", updatePosition);
};
},
[],
target
);
return readonly(position);
}
export {
useScroll as default
};