使用details和summary元素实现树形展示

1. 先看效果

image

2. 默认是关闭的,并且父级关闭后,子级的开关状态会被保留,再次展开时,可恢复;

image

3. 需要对details元素增加一个padding-left或margin-left,否则展开后,子级和父级是左对齐的,视觉效果不好;

4. 一般是details元素套一个summary元素和一个展开后要展示的内容,如果details中没有summary,则页面展示为"详细信息"

5. 可以监听details元素的toggle事件,元素展开时,也会自动加上open属性

details.addEventListener("toggle", event => {
  if (details.open) {
    /* the element was toggled open */
  } else {
    /* the element was toggled closed */
  }
});

image

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tree</title>
    <style>
        details {
            padding-left: 1em;
        }
    </style>
</head>
<body>
    <details>
        <summary>系统分类</summary>
        <details>
            <summary>系统一级</summary>
            111
        </details>
        <details>
            <summary>系统二级</summary>
            222
        </details>
    </details>

    <details>
        <summary>自定义分类</summary>
        <details>
            <summary>自定义一级</summary>
            333
        </details>
    </details>
</body>
</html>
posted @ 2023-05-18 14:58  pangqianjin  阅读(149)  评论(0编辑  收藏  举报