fix(utils): restore scrollIntoView method (#5973)

This commit is contained in:
jeremywu 2022-02-11 18:07:59 +08:00 committed by GitHub
parent 7569ccaf90
commit 04df2a483a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 3 deletions

View File

@ -33,6 +33,7 @@ import {
isEmpty,
unique,
castArray,
scrollIntoView,
} from '@element-plus/utils'
import {
EVENT_CODE,
@ -278,7 +279,7 @@ export default defineComponent({
const activeNode =
menuElement.querySelector('.el-cascader-node.is-active') ||
menuElement.querySelector('.el-cascader-node.in-active-path')
container?.scrollIntoView?.(activeNode)
scrollIntoView(container as HTMLElement, activeNode)
}
})
}

View File

@ -16,7 +16,7 @@ import {
CHANGE_EVENT,
EVENT_CODE,
} from '@element-plus/constants'
import { isKorean } from '@element-plus/utils'
import { isKorean, scrollIntoView } from '@element-plus/utils'
import { useLocale, useNamespace, useSize } from '@element-plus/hooks'
import { elFormKey, elFormItemKey } from '@element-plus/tokens'
@ -659,7 +659,7 @@ export const useSelect = (props, states: States, ctx) => {
'.el-select-dropdown__wrap'
)
if (menu) {
menu.scrollIntoView?.(target)
scrollIntoView(menu as HTMLElement, target)
}
}
scrollbar.value?.handleScroll()

View File

@ -60,3 +60,42 @@ export const getScrollBarWidth = (): number => {
return scrollBarWidth
}
/**
* Scroll with in the container element, positioning the **selected** element at the top
* of the container
*/
export function scrollIntoView(
container: HTMLElement,
selected: HTMLElement
): void {
if (!isClient) return
if (!selected) {
container.scrollTop = 0
return
}
const offsetParents: HTMLElement[] = []
let pointer = selected.offsetParent
while (
pointer !== null &&
container !== pointer &&
container.contains(pointer)
) {
offsetParents.push(pointer as HTMLElement)
pointer = (pointer as HTMLElement).offsetParent
}
const top =
selected.offsetTop +
offsetParents.reduce((prev, curr) => prev + curr.offsetTop, 0)
const bottom = top + selected.offsetHeight
const viewRectTop = container.scrollTop
const viewRectBottom = viewRectTop + container.clientHeight
if (top < viewRectTop) {
container.scrollTop = top
} else if (bottom > viewRectBottom) {
container.scrollTop = bottom - container.clientHeight
}
}