Skip to content

Commit

Permalink
fix(select): initially scroll to the active item in OptionGroup
Browse files Browse the repository at this point in the history
fix #3135
  • Loading branch information
moecasts committed Oct 15, 2024
1 parent 7e0bd73 commit 8a736b6
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 'tdesign-react/_util/helper';

Check failure on line 17 in src/select/base/Select.tsx

View workflow job for this annotation

GitHub Actions / call-test-build / build

Cannot find module 'tdesign-react/_util/helper' or its corresponding type declarations.

Check failure on line 17 in src/select/base/Select.tsx

View workflow job for this annotation

GitHub Actions / call-test-build / test

Cannot find module 'tdesign-react/_util/helper' or its corresponding type declarations.
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 8a736b6

Please sign in to comment.