Skip to content

Commit

Permalink
fix(select): initially scroll to the active item in OptionGroup (#3139)
Browse files Browse the repository at this point in the history
fix #3135
  • Loading branch information
moecasts authored Oct 16, 2024
1 parent 22f5730 commit 5aa771f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
17 changes: 17 additions & 0 deletions src/_util/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,20 @@ export function getPropsApiByEvent(eventName: string) {
export function pxCompat(param: string | number) {
return typeof param === 'number' ? `${param}px` : param;
}

/**
* 获取元素相对于容器(祖先)的偏移量
* @param element 目标元素
* @param container 容器元素
* @returns 相对于容器的偏移量
*/
export function getOffsetTopToContainer(element: HTMLElement, container: HTMLElement) {
let { offsetTop } = element;

let current = element.offsetParent as HTMLElement;
while (current && current !== container) {
offsetTop += current.offsetTop;
current = current.offsetParent as HTMLElement;
}
return offsetTop;
}
11 changes: 8 additions & 3 deletions src/select/base/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import classNames from 'classnames';
import isFunction from 'lodash/isFunction';
import get from 'lodash/get';
import debounce from 'lodash/debounce';
import { getOffsetTopToContainer } from '../../_util/helper';
import useControlled from '../../hooks/useControlled';
import { useLocaleReceiver } from '../../locale/LocalReceiver';
import useConfig from '../../hooks/useConfig';
Expand Down Expand Up @@ -385,12 +386,16 @@ const Select = forwardRefWithStatics(
const elementBottomHeight = parseInt(paddingBottom, 10) + parseInt(marginBottom, 10);
// 小于0时不需要特殊处理,会被设为0
const updateValue =
firstSelectedNode.offsetTop -
getOffsetTopToContainer(firstSelectedNode, content) -
content.offsetTop -
(content.clientHeight - firstSelectedNode.clientHeight) +
elementBottomHeight;
// eslint-disable-next-line no-param-reassign
content.scrollTop = updateValue;

// 通过 setTimeout 确保组件渲染完成后再设置 scrollTop
setTimeout(() => {
// eslint-disable-next-line no-param-reassign
content.scrollTop = updateValue;
});
}
};

Expand Down

0 comments on commit 5aa771f

Please sign in to comment.