做项目碰到一个需求,需要实现一个下拉框,点击下拉框内容显示,并且下拉框内容需要根据和屏幕的距离动态出现在下拉框的上方或者下方。
位置动态出现的代码:
const dropdownContent: any = useRef(null);
// 判断下拉框需要出现的位置
function adjustDropdownPosition(dropdownContent: any) {
if (dropdownContent) {
const { bottom } = dropdownContent.getBoundingClientRect();
const windowHeight = window.innerHeight;
if (bottom > windowHeight) {
dropdownContent.style.bottom = "100%";
} else {
dropdownContent.style.removeProperty("bottom");
}
}
}
// 每次执行时判断下拉框和屏幕的距离
useEffect(() => {
adjustDropdownPosition(dropdownContent.current);
});
return (
// css部分 需要将最外层div的positon设置为relative
<div className="dropdown dropdown-center">
....
<ul ref={dropdownContent}>
{...下拉框内容...}
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
)
每次点击下拉框之前,都会对比下拉框的位置和屏幕的距离,如果底部大于屏幕底部所剩余的距离,给内容<ul>添加样式bottom。