给出下面的例子
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>
为什么当按钮移出它的父按钮时,它会变成可点击的?
编辑:
我使用了 transform: translateY(50px);
来移动按钮,但是我们也可以使用 position:relative;top:50px;
来移动按钮问题依然存在。
最佳答案
您在这里遇到了一个隐藏的问题,翻译/不透明度在这里无关。当使用负数 z-index
时,就像您将元素放在 body
后面(因为这个元素的 z-index
设置为 自动
)。然后 body
高度由其流入内容(两个 div)定义,使用 translate 简单地将元素放置在 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 {
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>
body
是红色方 block ,所有元素都在它后面,按钮移到底部,不再被 body 覆盖。如果您使用其他属性移动按钮而不更改 body
高度,也会发生同样的情况。
如果你给 body 添加一些高度,translate 不会改变任何东西,因为按钮会保持在 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>
关于css - z-index 奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938062/