Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(select): initially scroll to the active item in OptionGroup #3139

Merged
merged 1 commit into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading