yandere_fe/src/services/offset_finder/offset_finder.service.js

32 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-09-24 14:21:55 -07:00
export const findOffset = (child, parent, { top = 0, left = 0 } = {}, ignorePadding = true) => {
const result = {
top: top + child.offsetTop,
left: left + child.offsetLeft
}
if (!ignorePadding && child !== window) {
2019-09-24 22:36:30 -07:00
const { topPadding, leftPadding } = findPadding(child)
2019-09-24 14:21:55 -07:00
result.top += ignorePadding ? 0 : topPadding
result.left += ignorePadding ? 0 : leftPadding
}
2019-09-24 22:36:30 -07:00
if (child.offsetParent && (parent === window || parent.contains(child.offsetParent) || parent === child.offsetParent)) {
2019-09-24 14:21:55 -07:00
return findOffset(child.offsetParent, parent, result, false)
} else {
2019-09-24 22:43:02 -07:00
if (parent !== window) {
const { topPadding, leftPadding } = findPadding(parent)
result.top += topPadding
result.left += leftPadding
}
2019-09-24 14:21:55 -07:00
return result
}
}
2019-09-24 22:36:30 -07:00
const findPadding = (el) => {
const topPaddingStr = window.getComputedStyle(el)['padding-top']
const topPadding = Number(topPaddingStr.substring(0, topPaddingStr.length - 2))
const leftPaddingStr = window.getComputedStyle(el)['padding-left']
const leftPadding = Number(leftPaddingStr.substring(0, leftPaddingStr.length - 2))
return { topPadding, leftPadding }
}