Skip to content

下面的代码非常经典

既考察了伪元素,又考察了三角形写法,又考察了绝度定位的居中写法

jsx
<Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          // horizontal: 'center',
        }}
        // Adding will cause components to move unexpectedly,右边距离不够就不能设置这个
        // transformOrigin={{
        //   vertical: 'top',
        //   horizontal: 'right',
        // }}
        keepMounted={false}
        PaperProps={{
          sx: {
            // 让 Paper 有足够的上边距,给箭头腾出空间
            mt: 1.5,
            // 允许三角形箭头溢出 ——> 这个也是前提
            overflow: "visible",
            // 使用伪元素 ::before 来画箭头
            "::before": {
              //0.伪元素设置
              content: '""',
              display: "block",
              //1.三角形
              // 三角形尺寸
              width: 0,
              height: 0,
              // 三角形边框
              borderLeft: "8px solid transparent",
              borderRight: "8px solid transparent",
              borderBottom: "8px solid #fff", // 箭头颜色
              //2.绝对定位居中
              position: "absolute",
              // 让箭头出现在 Paper 顶部
              top: 0,
              // 箭头水平居中(可根据实际情况微调)
              left: "46%",
              transform: "translateX(-50%) translateY(-100%)", //translateY(-100%)是为了让自身浮出去
            },
          },
        }}
      >
        <MemberNotification getNotificationList={getNotificationList} markNotificationAsRead={markNotificationAsRead} setBadgeContent={setBadgeContent} badgeContent={badgeContent} />
      </Popover>

**top: 0;**让箭头的底边紧贴 PopoverPaper 顶部。

**left: "46%";**让箭头大致位于 Paper 顶部的 46% 位置(即接近 IconButton)。

translateX(-50%): 向左移动自身宽度的 50%(即小三角居中对齐)。

translateY(-100%): 向上移动自身高度的 100%(即小三角完全浮出 PopoverPaper 顶部)。