You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
3.2 KiB

2 years ago
# z-index解析以及在FineUI中使用原则
z-index问题一直是前端开发人员的噩梦
代码review过程中反复强调z-index解析以及在FineUI中使用原则:
<b>"不要滥用z-index,只有当你充分理解原理并确定要通过z-index解决的时候,方可使用"</b>
从直觉上,z-index越大的元素排在上面是理所当然的,但是实际上这是不全面的,z-index不是全局的,设置了z-index的元素只会和与他处在同一stacking contexts的元素进行比较
可以思考一下,为什么我们的气泡默认的container属性是body呢,不可以放到当前的容器里面吗?因为stacking contexts的关系,即使弹出气泡的z-index很大,也会出现被遮住的情况
```javascript
BI.createWidget({
type: "bi.horizontal_auto",
items: [
{
type: "bi.label",
text: "我的z-index是2",
height: 50,
width: 100,
cls: "bi-background bi-border",
css: {
zIndex: 2,
},
}, {
type: "bi.horizontal_auto",
css: {
zIndex: 1, // 因为这里产生了一个stacking context,因此无论popup的z-index多高,他都会在label的下面
},
items: [
{
type: "bi.bubble_combo",
width: 100,
height: 30,
el: {
type: "bi.button",
text: "点击弹出",
},
container: this, // 默认container为body,这里手动改为当前元素
direction: "top",
popup: {
el: {
type: "bi.label",
text: "我的z-index是10000000",
},
},
},
],
},
],
});
```
![示例1](../images/38.png)
## 创建stacking contexts的几种方式
详细场景可以参考MDN文档,这里只列举几个常见的
[the_stacking_context](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context#the_stacking_context)
- html根节点
- opacity的值小于1
- position:absolute 或 position:relative 且带有z-index属性
- position:fixed 或 position:sticky
- 父容器是 display:flex 或 display:grid 且子元素自己带有z-index属性
- transform属性
2 years ago
- isolation: isolation 直接创建上下文,这是一个毫无副作用无痛创建stacking context的方式
2 years ago
如果觉得通过查看代码不能够直观的分辨stacking contexts,那么推荐一个插件[CSS Stacking Context inspector](https://chrome.google.com/webstore/detail/css-stacking-context-insp/apjeljpachdcjkgnamgppgfkmddadcki)
能够自动识别stacking context结构,并注明产生stacking context的原因
![示例2](../images/37.png)
## 在什么情况下需要使用z-index来解决问题呢
除FineUI内部使用z-index之外,常见业务开发中使用z-index的例子
1. 在某个元素上悬浮显示,且超出容器边界的,例如拖拽宽度的图标.
2. 仪表板组件自由排列叠放布局
3. 没了