如何防止自定义弹出框超出屏幕范围

3

我正在尝试创建一个没有任何库的自定义模态框。这个模态框显示当前用户,根据活跃用户的数量,它可能会变得非常大。如果模态框中的元素数量超过屏幕底部,我就无法看到整个模态框。

理想情况下,我希望模态框始终居中且包含在屏幕内,如果元素太多,用户可以通过滚动模态框来查看而不会移动背景。非常感谢任何帮助!

目前我已经达到了以下效果,但离正确还差很远。这个模态框没有滚动功能,如果它变得太大,它将被屏幕裁剪:

const Modal: React.FC<IModalProps> = (props) => {
  

     if (!props.isOpen) {
       return null;
     }

  return (
    <>
         <ModalBackgroundStyled onClick={props.onCloseRequest}/>
            <ModalWrapper>
                {props?.users?.map(user=>{
                    return(
                        <NamePlate user={user}/>
                    );
                })}
            </ModalWrapper>
    </>
    )
};

export default Modal;

     const ModalBackgroundStyled = styled.div`
     background-color: rgba(255,255,255,0.5);
     backdrop-filter: blur(2px);
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     z-index: 1;
     height:200%;
     width:200%;
     display: flex;
     justify-content: center;
     align-items: center;
   `;

const ModalStyled = styled.div`

    display:flex;
    flex-direction: column;
    align-items:center;
    background: #E5E5E5;
    border-radius: 4px;
    overflow: auto;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%);
    min-width: 30rem;
    z-index: 2;
`;

1
最大宽度:100%;最大高度:100%; - Someone_who_likes_SE
1个回答

2
如果您希望模态框的内容适应屏幕高度,并在模态框的内容超出屏幕高度时显示滚动条,您应该将 ModalWrappermax-height 设置为小于或等于视图高度,并将 overflow-y 设置为 scroll。请参见下面的示例:
const ModalWrapper = styled.div`
      max-height:100vh;
      overflow-y:scroll;
`;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接