details 标签
在以往的项目中去实现如下效果,我一般是使用 HTML
+ JS
去完成的,但今天我了解到一个很便捷的方法可以帮助我只使用 HTML
就可以快速的完成如下效果。那就是 HTML5
中新增的 detils
标签。
基本介绍
实现代码如下:
<details>
<summary>
文章概要
</summary>
<div>文章内容文章内容文章内容文章内容文章内容文章内容文章内容文章内容</div>
</details>
details
为包裹元素标签summary
代表的是标题并且在前面显示一个小三角其他标签
可渲染成内容
summary 省略:
summary
省略后标题自动显示 详细信息
属性
open 属性
open
其值得类型为 Boolean
,作用为控制元素的显示/隐藏
<details open>
<summary >
文章概要
</summary>
<div>文章内容文章内容文章内容文章内容文章内容文章内容文章内容文章内容</div>
</details>
自定义 UI
设置样式
details summary {
/* 文字从右到左 */
direction: rtl;
/* 容器缩小到文字大小 */
width: fit-content;
}
/* 选中三角符号 */
details ::marker {
direction: ltr;
color: gray;
}
<details open>
<summary>
文章概要
</summary>
<div>文章内容文章内容文章内容文章内容文章内容文章内容文章内容文章内容</div>
</details>
效果如下:
替换 UI
details summary {
/* 容器缩小到文字大小 */
width: fit-content;
height: 20px;
line-height: 20px;
}
/* 隐藏原始三角 */
details ::marker {
font-size: 0;
}
/* 自定义三角 */
summary::after {
content: '▶';
margin-left: .5ch;
position: absolute;
transition: transform .2s;
}
details:not([open]) summary::after {
transform: rotate(90deg);
}
<details open>
<summary>
文章概要
</summary>
<div>文章内容文章内容文章内容文章内容文章内容文章内容文章内容文章内容</div>
</details>
效果如下:
实际交互
无JS实现点击显示悬浮菜单,自定义下拉框等效果
nav {
background: #eee;
padding-left: 40px;
}
details summary {
width: fit-content;
padding: 5px 28px;
height: 28px;
line-height: 28px;
}
/* 打开或悬停样式 */
[open] summary,
details summary:hover {
background-color: #fff;
box-shadow: inset 1px 0 #eee, inset -1px 0 #eee;
}
/* 隐藏原始三角 */
details ::marker {
font-size: 0;
}
/* 自定义三角 */
summary::after {
content: '▼';
margin-left: .3ch;
color: grey;
position: absolute;
transition: transform .2s;
}
details:not([open]) summary::after {
transform: rotate(-90deg);
}
/* 打开开启全屏遮罩 */
[open] summary::before {
content: '';
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.box {
position: absolute;
min-width: 120px;
border: 1px solid #ddd;
border-top: 0;
box-sizing: border-box;
}
.box div{
padding: 8px 10px;
cursor: pointer;
}
.box div:hover{
background: #eee;
}
.box div sup{
display: inline-block;
width: 18px;
height: 18px;
text-align: center;
line-height: 18px;
border-radius: 50%;
color: #fff;
background: #d50000;
}
<nav>
<details open>
<summary>
我的消息
</summary>
<div class="box">
<div>我的私信<sup>12</sup></div>
<div>我的回答</div>
<div>我的关注</div>
</div>
</details>
</nav>
效果如下: