简体   繁体   English

z-index 奇怪的行为?

[英]z-index weird behavior?

Given the example below鉴于下面的例子

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index: -99; opacity: .5; position: relative; } .d2>button { transform: translateY(50px); }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

Why when the button moves outside it's parent, it become clickable ?为什么当按钮移出它的父级时,它变得可点击?

EDIT:编辑:

I used transform: translateY(50px);我使用了transform: translateY(50px); to move the button, however we can also use position:relative;top:50px;移动按钮,但是我们也可以使用position:relative;top:50px; to move the button yet the problem still remains.移动按钮但问题仍然存在。

Here you are facing a hidden issue and translate/opacity has nothing to do here.在这里,您面临一个隐藏的问题,而翻译/不透明度在这里无关。 When using negative z-index it's like you made your elements to be behind the body (since this one has a z-index set to auto ).使用负z-index ,就像您将元素置于body后面(因为此元素的z-index设置为auto )。 Then the body height is defined by its in-flow content (both divs) and using translate simply made the element to be placed below the body thus we can reach it and click it.然后body高度由它的流入内容(两个 div)定义,使用 translate 简单地将元素放置在 body 下方,因此我们可以到达它并单击它。

let's add some border/background to better see the issue:让我们添加一些边框/背景以更好地查看问题:

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index:-1; position: relative; } .d2>button { transform: translateY(50px); } body { background:rgba(255,0,0,0.5); border:2px solid; } html { background:blue; }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

The body is the red square, all your element are behind it and the button is moved to the bottom and no more covered by the body. body是红色方块,你所有的元素都在它后面,按钮被移到底部,不再被身体覆盖。 The same will also happen if you move your button using other properties without changing the body height.如果您使用其他属性移动按钮而不更改body高度,也会发生同样的情况。

If you add some height to the body, translate won't change anything as the button will kept behind the body如果你给身体增加一些高度,翻译不会改变任何东西,因为按钮将保持在body后面

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index: -1; position: relative; } .d2>button { transform: translateY(50px); } body { height:100vh; }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM